I have a string which contains multiple items separated by commas :
string RESULT = "D_CA, P_AMOUNT ,D_SH,D_CU,D_TO,D_GO,D_LE,D_NU,D_CO,D_MU,D_PMU,D_DP, P_COMMENT ";
As you can see some elements contain Whitespaces, My object is to remove all the whitespaces, This is my code:
RESULT.Split(',').ToList().ForEach(p =>
if (p.Contains(" "))
{
RESULT = RESULT.Replace(p, p.Trim());
}
});
And this is my result:
"D_CA,P_AMOUNT,D_SH,D_CU,D_TO,D_GO,D_LE,D_NU,D_CO,D_MU,D_PMU,D_DP,P_COMMENT"
it works well, But I ask if there is another more optimized way to get the same result?
strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.
For those who are trying to remove space in the middle of a string, use [yourString stringByReplacingOccurrencesOfString:@" " withString:@""] .
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
I suppose you need the string with whitespaces removed. You could use String.Replace()
RESULT = RESULT.Replace(" ",string.Empty);
Alternatively, you could also use Regex for replace,
RESULT = Regex.Replace(RESULT,@"\s",string.Empty);
The regex approach would ensure replacement of all whitespace characters including tab,space etc
See the answer by Pavel Anikhouski, which checks the performance of all suggested solutions and actually shows that the simplified LINQ solution does not help performance too much - good to know :-) .
Simpler solution with LINQ:
string.Join(string.Empty, input.Where(c=>!char.IsWhiteSpace(c)));
First we filter away all whitespace characters and then we join them into a string. This has only one string allocation (to create the resulting string) and handles all kinds of whitespace characters, not only spaces.
Use a StringBuilder
to build up the resulting string and then go through the input string with a foreach
, always checking char.IsWhiteSpace(character)
. In case the character is not whitespace, append it in the StringBuilder
by calling Append(character)
method. At the end just return the resulting string by calling ToString()
on the StringBuilder
.
var builder = new StringBuilder();
foreach(var character in input)
{
if (!char.IsWhiteSpace(character))
{
builder.Append(character);
}
}
return builder.ToString();
This implementation is more efficient, as it does not produce any string allocations, except for the end result. It just works with the input string and reads it once.
Isn't what you looking for?
var noWhiteSpaces = RESULT.Replace(" ", string.Empty);
You can Trim()
:
var split = RESULT.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s=> s.Trim());
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