Tony D
Tony D

Reputation: 1531

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 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

Answers (5)

Jack Ryan
Jack Ryan

Reputation: 8472

I like this for readability:

trimMe.Split(' ').First();

Upvotes: 11

Ahmad Mageed
Ahmad Mageed

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

JSBձոգչ
JSBձոգչ

Reputation: 41378

Similar to another answer, but terser:

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

Upvotes: 5

Randolpho
Randolpho

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

Lasse V. Karlsen
Lasse V. Karlsen

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

Related Questions