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.
\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 ).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With