Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast and clever way to get the NON FIRST segment of a C# string

Tags:

I do a split(' ') over an string and I want to pull the first element of the returned string in order to get the rest of the string.

f.e. "THIS IS AN AMAZING STRING".split(' ');

I want to get all the words but THIS. This is: IS AN AMAZING STRING

The string will always have at least one blank space between the first and the second word because I will put it hard coded

Is there a function that makes this? thank you

like image 683
anmarti Avatar asked Nov 12 '12 17:11

anmarti


2 Answers

try

string X = "THIS IS AN AMAZING STRING";
string Y = (X.IndexOf ( " " ) < 0) ? string.Empty : X.Substring (X.IndexOf ( " " )  + 1); // Y = IS AN AMAZING STRING

As per comment (IF X is guaranteed to be a valid string with at least one space) a simpler version without checking etc.:

string Y = X.Substring (X.IndexOf ( " " )  + 1); 
like image 154
Yahia Avatar answered Sep 22 '22 13:09

Yahia


A fairly good option would be to use:

string original = "THIS IS AN AMAZING STRING";
string[] split = original.Split(new []{' '}, 2);
string result = split[1];

Note that, if you just want the resulting string, you can shorten this:

var result = original.Split(new []{' '}, 2)[1];

By using the overload of string.Split which takes a max number of splits, you avoid the need to join as well as the extra overhead.

like image 42
Reed Copsey Avatar answered Sep 21 '22 13:09

Reed Copsey