I am building a string of last names separated by hyphens. Sometimes a whitespace gets caught in there. I need to remove all whitespace from end result.
Sample string to work on:
Anderson -Reed-Smith
It needs to end up as (no space after Anderson):
Anderson-Reed-Smith
The last name string is in a string variable, LastName.
I am using a regular expression:
Regex.Replace(LastName, @"[\s+]", "");
The result of this is:
Anderson -Reed-Smith.
I also tried:
Regex.Replace(LastName, @"\s+", "");
and
Regex.Replace(LastName, @"\s", "");
What am I doing wrong?
Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
The standard solution is to use the std::remove_if algorithm to remove whitespace characters from std::string using the Erase-remove idiom technique.
The trim() function removes whitespace and other predefined characters from both sides of a string.
Instead of a RegEx
use Replace
for something that simple:
LastName = LastName.Replace(" ", String.Empty);
Regex.Replace
does not modify its first argument (recall that strings are immutable in .NET) so the call
Regex.Replace(LastName, @"\s+", "");
leaves the LastName
string unchanged. You need to call it like this:
LastName = Regex.Replace(LastName, @"\s+", "");
All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.
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