randomUser1212421
randomUser1212421

Reputation: 15

Taking parts out of a string, how?

So I have a server that receives a connection with the message being converted to a string, I then have this string split between by the spaces

Upvotes: 0

Views: 102

Answers (4)

Caius Jard
Caius Jard

Reputation: 74605

If you're just removing the first word of a string, you don't need to use Split at all; doing a Substring after you found the space will be more efficient.

var line = ...
var idx = line.IndexOf(' ')+1;
line = line.Substring(idx);

or in recent C# versions

line = line[idx..];

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283634

Assuming that you only want to remove the first word and not all repeats of it, a much more efficient way is to use the overload of split that lets you control the maximum number of splits (the argument is the maximum number of results, which is one more than the maximum number of splits):

string[] arguments = line.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); // split only once
User.data = arguments.Skip(1).FirstOrDefault();

arguments[1] does the right thing when there are "more" arguments, but throw IndexOutOfRangeException if the number of words is zero or one. That could be fixed without LINQ by (arguments.Length > 1)? arguments[1]: string.Empty

Upvotes: 0

Caius Jard
Caius Jard

Reputation: 74605

So you have a line:

var line = "hello world my name is bob";

And you don't want "world" or "is", so you want:

"hello my name bob"

If you split to a list, remove the things you don't want and recombine to a line, you won't have extraneous spaces:

var list = line.Split().ToList();
list.Remove("world");
list.Remove("is");
var result = string.Join(" ", list);

Or if you know the exact index positions of your list items, you can use RemoveAt, but remove them in order from highest index to lowest, because if you e.g. want to remove 1 and 4, removing 1 first will mean that the 4 you wanted to remove is now in index 3.. Example:

var list = line.Split().ToList();
list.RemoveAt(4); //is
list.RemoveAt(1); //world
var result = string.Join(" ", list);

If you're seeking a behavior that is like string.Replace, which removes all occurrences, you can use RemoveAll:

var line = "hello is world is my is name is bob";

var list = line.Split().ToList();
list.RemoveAll(w => w == "is"); //every occurence of "is"
var result = string.Join(" ", list);

Upvotes: 2

You could remove the empty space using TrimStart() method. Something like this:

    string text = "Hello World";
    string[] textSplited = text.Split(' ');

    string result = text.Replace(textSplited[0], "").TrimStart();

Upvotes: 0

Related Questions