c# Fastest way to remove extra white spaces

2019-01-13 17:34发布

What is the fastest way to replace extra white spaces to one white space?
e.g.

from

foo      bar 

to

foo bar

23条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-13 18:18

This piece of code works good. I have not measure the performance.

string text = "   hello    -  world,  here   we go  !!!    a  bc    ";
string.Join(" ", text.Split().Where(x => x != ""));
// Output
// "hello - world, here we go !!! a bc"
查看更多
Ridiculous、
3楼-- · 2019-01-13 18:20

try this:

System.Text.RegularExpressions.Regex.Replace(input, @"\s+", " ");
查看更多
【Aperson】
4楼-- · 2019-01-13 18:20

For those who just want to copy-pase and go on:

    private string RemoveExcessiveWhitespace(string value)
    {
        if (value == null) { return null; }

        var builder = new StringBuilder();
        var ignoreWhitespace = false;
        foreach (var c in value)
        {
            if (!ignoreWhitespace || c != ' ')
            {
                builder.Append(c);
            }
            ignoreWhitespace = c == ' ';
        }
        return builder.ToString();
    }
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-13 18:20

It's very simple, just use the .Replace() method:

string words = "Hello     world!";
words = words.Replace("\\s+", " ");

Output >>> "Hello world!"

查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-13 18:21

I've tried using StringBuilder to:

  1. remove extra whitespace substrings
  2. accept characters from looping over the original string, as Blindy suggests

Here's the best balance of performance & readability I've found (using 100,000 iteration timing runs). Sometimes this tests faster than a less-legible version, at most 5% slower. On my small test string, regex takes 4.24x as much time.

public static string RemoveExtraWhitespace(string str)
    {
        var sb = new StringBuilder();
        var prevIsWhitespace = false;
        foreach (var ch in str)
        {
            var isWhitespace = char.IsWhiteSpace(ch);
            if (prevIsWhitespace && isWhitespace)
            {
                continue;
            }
            sb.Append(ch);
            prevIsWhitespace = isWhitespace;
        }
        return sb.ToString();
    }
查看更多
叼着烟拽天下
7楼-- · 2019-01-13 18:21

There is no need for complex code! Here is a simple code that will remove any duplicates:

public static String RemoveCharOccurence(String s, char[] remove)
{
    String s1 = s;
    foreach(char c in remove)
    {
        s1 = RemoveCharOccurence(s1, c);
    }

    return s1;
}

public static String RemoveCharOccurence(String s, char remove)
{
    StringBuilder sb = new StringBuilder(s.Length);

    Boolean removeNextIfMatch = false;
    foreach(char c in s)
    {
        if(c == remove)
        {
            if(removeNextIfMatch)
                continue;
            else
                removeNextIfMatch = true;
        }
        else
            removeNextIfMatch = false;

        sb.Append(c);
    }

    return sb.ToString();
}
查看更多
登录 后发表回答