Reputation: 7900
I have a lot of strings that look like this:
current affairs
and i want to make the string be :
current affairs
i try to use Trim()
but it won't do the job
Upvotes: 4
Views: 335
Reputation: 25143
Using Regex here is the way,
System.Text.RegularExpressions.Regex.Replace(input, @”\s+”, ” “);
This will removes all whitespace characters including tabs, newlines etc.
Upvotes: 0
Reputation: 289
First you need to split the whole string and then apply trim to each item.
string [] words = text.Split(' ');
text="";
forearch(string s in words){
text+=s.Trim();
}
//text should be ok at this time
Upvotes: -1
Reputation: 2098
You can use a regex:
public string RemoveMultipleSpaces(string s)
{
return Regex.Replace(value, @"\s+", " ");
}
After:
string s = "current affairs ";
s = RemoveMultipleSpaces(s);
Upvotes: 0
Reputation: 1136
Use a regular expression.
yourString= Regex.Replace(yourString, @"\s+", " ");
Upvotes: 0
Reputation: 86346
Regex can do the job
string_text = Regex.Replace(string_text, @"\s+", " ");
Upvotes: 11
Reputation: 498934
You can use regular expressions for this, see Regex.Replace
:
var normalizedString = Regex.Replace(myString, " +", " ");
If you want all types of whitespace, use @"\s+"
instead of " +"
which just deals with spaces.
var normalizedString = Regex.Replace(myString, @"\s+", " ");
Upvotes: 6