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条回答
Summer. ? 凉城
2楼-- · 2019-01-13 18:02

A few requirements are not clear in this question which deserve some thought.

  1. Do you want a single leading or trailing white space character?
  2. When you replace all white space with a single character, do you want that character to be consistent? (i.e. many of these solutions would replace \t\t with \t and ' ' with ' '.

This is a very efficient version which replaces all white space with a single space and removes any leading and trailing white space prior to the for loop.

  public static string WhiteSpaceToSingleSpaces(string input)
  {
    if (input.Length < 2) 
        return input;

    StringBuilder sb = new StringBuilder();

    input = input.Trim();
    char lastChar = input[0];
    bool lastCharWhiteSpace = false;

    for (int i = 1; i < input.Length; i++)
    {
        bool whiteSpace = char.IsWhiteSpace(input[i]);

        //Skip duplicate whitespace characters
        if (whiteSpace && lastCharWhiteSpace)
            continue;

        //Replace all whitespace with a single space.
        if (whiteSpace)
            sb.Append(' ');
        else
            sb.Append(input[i]);

        //Keep track of the last character's whitespace status
        lastCharWhiteSpace = whiteSpace;
    }

    return sb.ToString();
  }
查看更多
Rolldiameter
3楼-- · 2019-01-13 18:04
string yourWord = "beep boop    baap beep   boop    baap             beep";

yourWord = yourWord .Replace("  ", " |").Replace("| ", "").Replace("|", "");
查看更多
老娘就宠你
4楼-- · 2019-01-13 18:04
public string GetCorrectString(string IncorrectString)
    {
        string[] strarray = IncorrectString.Split(' ');
        var sb = new StringBuilder();
        foreach (var str in strarray)
        {
            if (str != string.Empty)
            {
                sb.Append(str).Append(' ');
            }
        }
        return sb.ToString().Trim();
    }
查看更多
神经病院院长
5楼-- · 2019-01-13 18:05

I know this is really old, but the easiest way to compact whitespace (replace any recurring whitespace character with a single "space" character) is as follows:

    public static string CompactWhitespace(string astring)
    {
        if (!string.IsNullOrEmpty(astring))
        {
            bool found = false;
            StringBuilder buff = new StringBuilder();

            foreach (char chr in astring.Trim())
            {
                if (char.IsWhiteSpace(chr))
                {
                    if (found)
                    {
                        continue;
                    }

                    found = true;
                    buff.Append(' ');
                }
                else
                {
                    if (found)
                    {
                        found = false;
                    }

                    buff.Append(chr);
                }
            }

            return buff.ToString();
        }

        return string.Empty;
    }
查看更多
不美不萌又怎样
6楼-- · 2019-01-13 18:07
public static string RemoveExtraSpaces(string input)
{
    input = input.Trim();
    string output = "";
    bool WasLastCharSpace = false;
    for (int i = 0; i < input.Length; i++)
    {
        if (input[i] == ' ' && WasLastCharSpace)
            continue;
        WasLastCharSpace = input[i] == ' ';
        output += input[i];
    }
    return output;
}
查看更多
虎瘦雄心在
7楼-- · 2019-01-13 18:10
string text = "foo       bar";
text = Regex.Replace(text, @"\s+", " ");
// text = "foo bar"

This solution works with spaces, tabs, and newline. If you want just spaces, replace '\s' with ' '.

查看更多
登录 后发表回答