Discard Chars After Space In C# String
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 开发者_JS百科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.
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.
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
I like this for readability:
trimMe.Split(' ').First();
Similar to another answer, but terser:
int indexSpace = trimMe.IndexOf(" ");
return trimMe.Substring(0, indexSpace >= 0 ? indexSpace : trimMe.Length);
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.
精彩评论