tags:

views:

230

answers:

5

I would like to discard the remaining characters (which can be any characters) in my string after I encounter a space.
Eg. I would like the string "10 1/2" to become "10";
Currently I'm using Split, but this seems like overkill:

string TrimMe = "10 1/2";
string[] cleaned = TrimMe.Split(new char[] {' '});
return string[0];

I feel there should be an easier way.

+10  A: 

This should work:

Int32 indexOfSpace = TrimMe.IndexOf(' ');
if (indexOfSpace == 0)
    return String.Empty; // space was first character
else if (indexOfSpace > 0)
    return TrimMe.Substring(0, indexOfSpace);
else
    return TrimMe; // no space found
Lasse V. Karlsen
+1 - extra points for the "corner cases"
Fredrik Mörk
Not entirely sure it was needed though, looks like Substring handles length=0 anyway. I'll leave it though.
Lasse V. Karlsen
+1  A: 

Split is probably your most elegant/easiest solution. Other options include regular expressions and/or parsing/lexical analysis. Both will be more complex than the example you've provided calls for.

Randolpho
+5  A: 

Similar to another answer, but terser:

int indexSpace = trimMe.IndexOf(" ");
return trimMe.Substring(0, indexSpace >= 0 ? indexSpace : trimMe.Length);
JSBangs
+3  A: 

Some other options:

string result = Regex.Match(TrimMe, "^[^ ]+").Value;
// or
string result = new string(TrimMe.TakeWhile(c => c != ' ').ToArray());

However, IMO what you started with is much simpler and easier to read.

EDIT: Both solutions will handle empty strings, return the original if no spaces were found, and return an empty string if it starts with a space.

Ahmad Mageed
Your linq answer is clever, but I think you're right, I'll stick with my split solution. Thank you.
Tony D
I agree... the LINQ answer is quite clever. I'd hate to see it in production code. :)
Randolpho
+4  A: 

I like this for readability:

trimMe.Split(' ').First();
Jack Ryan
Me too. Very nice.
Tony D