Reputation: 1531
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 cleaned[0];
I feel there should be an easier way.
Upvotes: 14
Views: 8005
Reputation: 96477
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.
Upvotes: 12
Reputation: 41378
Similar to another answer, but terser:
int indexSpace = trimMe.IndexOf(" ");
return trimMe.Substring(0, indexSpace >= 0 ? indexSpace : trimMe.Length);
Upvotes: 5
Reputation: 56391
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.
Upvotes: 1
Reputation: 391306
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
Upvotes: 11