Discard Chars After Space In C# String

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();

Tags:

C#

.Net

String