Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discard Chars After Space In C# String

Tags:

string

c#

.net

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.

like image 421
Tony D Avatar asked Oct 21 '09 14:10

Tony D


People also ask

What is the purpose of '\ 0 character in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case. The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0 ).

How do I delete all characters after a character in C++?

We can use the substr() function to delete all characters after a specific character in a string. But for that, first, we need to look for the given character in the string using the string::find() function.

How does C handle whitespace?

When parsing code, the C compiler ignores white-space characters unless you use them as separators or as components of character constants or string literals. Use white-space characters to make a program more readable. Note that the compiler also treats comments as white space.


2 Answers

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.

like image 107
Ahmad Mageed Avatar answered Oct 25 '22 13:10

Ahmad Mageed


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
like image 11
Lasse V. Karlsen Avatar answered Oct 25 '22 13:10

Lasse V. Karlsen