How to Replace Multiple Spaces With a Single Space in C#

How do I replace multiple spaces with a single space in C#?


string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");

How to replace multiple spaces with single space?

You can match the following:

@"\s+"

and replace with:

" "

Regex.Replace("Have       a   Nice              Day !  !!", @"\s+", " ");

Trying to replace all white space with a single space

You can do this -

System.Text.RegularExpressions.Regex.Replace(str,@"\s+"," ");

where str is your string.

How to replace multiple white spaces with one white space


string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");

Regex for replacing multiple white spaces with multiple  

Use a match evaluator to build the custom replacement:

var s = " 1  2   3    4 ";
var result = Regex.Replace(s, @"\s{2,}", m =>
string.Concat(Enumerable.Repeat(" ", m.Length)));
Console.WriteLine(result);
// => ' 1  2   3    4 '

See the C# demo

Here, \s{2,} matches 2 or more whitespaces, the match is assigned to m inside the match evaluator, and string.Concat(Enumerable.Repeat(" ", m.Length)) builds a string that consists of   substrings of match length times (see this thread).

c# Fastest way to remove extra white spaces

The fastest way? Iterate over the string and build a second copy in a StringBuilder character by character, only copying one space for each group of spaces.

The easier to type Replace variants will create a bucket load of extra strings (or waste time building the regex DFA).

Edit with comparison results:

Using http://ideone.com/NV6EzU, with n=50 (had to reduce it on ideone because it took so long they had to kill my process), I get:

Regex: 7771ms.

Stringbuilder: 894ms.

Which is indeed as expected, Regex is horribly inefficient for something this simple.

C# Replacing Multiple Spaces with 1 space leaving special characters intact

In your example the data is delimited by position, not by characters; is that correct? If so, you should extract by position; something like:

foreach (string s in output.Split())
{
var sessionName = s.Substring(0, 18).Trim();
var userName = s.Substring(18, 19).Trim();
var id = Int32.Parse(s.Substring(37, 8).Trim());
var whateverType = s.Substring(45, 12).Trim();
var device = s.Substring(57, 6).Trim();
}

Of course you need to do proper error checking, and should probably put the field widths in an array and calculate positions instead of hard-coding them as I have shown.

Removing multiple whitespace, c#

What about

string.Join(" ", 
myString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))

Edit

As extension

    public static string RemoveWhiteSpaces(this string s)
{
return string.Join(" ", s.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries));
}
myString.RemoveWhiteSpaces();

How to replace multiple whitespaces without modifying newline characters?

Try this:

line = Regex.Replace(line, @"\t+", " ");
line = Regex.Replace(line, @" +", " ");

It translates the string "a b c\t\t\t\nd e f" to a b c \nd e f




For an explanation see for example: http://www.ntu.edu.sg/home/ehchua/programming/howto/Regexe.html :

The \s (lowercase s) matches a whitespace (blank, tab \t, form-feed \f and newline \r or \n).



Related Topics



Leave a reply



Submit