How can I replace multiple spaces in a string with only one space in C#?
Example "1 2 3 4 5" would be : "1 2 3 4 5"?
How can I replace multiple spaces in a string with only one space in C#?
Example "1 2 3 4 5" would be : "1 2 3 4 5"?
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);
tempo = regex.Replace(tempo, @" ");
string xyz = "1 2 3 4 5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
while (str.IndexOf(" ") != -1)
str = str.Replace(" ", " ");
Non regex way.
Consolodating other answers, per Joel, and hopefully improving slightly as I go:
You can do this with Regex.Replace()
:
string s = Regex.Replace (
" 1 2 4 5",
@"[ ]{2,}",
" "
);
Or with String.Split()
:
static class StringExtensions
{
public static string Join(this IList<string> value, string separator)
{
return string.Join(separator, value.ToArray());
}
}
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");
It's much simpler than all that:
while(str.Contains(" ")) str = str.Replace(" ", " ");
I like to use:
myString = Regex.Replace(myString, @"\s+", " ");
Since it will catch runs of any kind of whitespace (e.g. tabs, newlines, etc.) and replace them with a single space.
If this is in a lengthy loop with optimization concerns, I would suggest doing a timing comparison of the given solutions with a simple char array copy that skips the extra spaces.
I just wrote a new Join
that I like, so I thought I'd re-answer, with it:
public static string Join<T>(this IEnumerable<T> source, string separator)
{
return string.Join(separator, source.Select(e => e.ToString()).ToArray());
}
One of the cool things about this is that it work with collections that aren't strings, by calling ToString() on the elements. Usage is still the same:
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");
I think Matt's answer is the best, but I don't believe it's quite right. If you want to replace newlines, you must use:
myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);