代码之家  ›  专栏  ›  技术社区  ›  Matt W

删除内部重复空间[重复]

  •  0
  • Matt W  · 技术社区  · 6 年前

    例子:

    1 2 3  4    5
    

    将是:

    1 2 3 4 5
    
    0 回复  |  直到 12 年前
        1
  •  439
  •   Sheridan    9 年前
    RegexOptions options = RegexOptions.None;
    Regex regex = new Regex("[ ]{2,}", options);     
    tempo = regex.Replace(tempo, " ");
    
        2
  •  596
  •   Matt    16 年前

    我喜欢使用:

    myString = Regex.Replace(myString, @"\s+", " ");
    

    因为它将捕获任何类型的空白(如制表符、换行符等)并用一个空格替换它们。

        3
  •  46
  •   tvanfosson    16 年前
    string xyz = "1   2   3   4   5";
    xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
    
        4
  •  38
  •   Brenda Bell    14 年前

    我认为马特的回答是最好的,但我不认为这是完全正确的。如果要替换换行符,必须使用:

    myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);
    
        5
  •  25
  •   cuongle    12 年前

    使用LINQ的另一种方法:

     var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
     str = string.Join(" ", list);
    
        6
  •  22
  •   Fahim Parkar    12 年前

    while(str.Contains("  ")) str = str.Replace("  ", " ");
    
        7
  •  21
  •   ScubaSteve    9 年前

    即使是简单的任务,Regex也可能相当慢。这将创建一个扩展方法,可以在 string

        public static class StringExtension
        {
            public static String ReduceWhitespace(this String value)
            {
                var newString = new StringBuilder();
                bool previousIsWhitespace = false;
                for (int i = 0; i < value.Length; i++)
                {
                    if (Char.IsWhiteSpace(value[i]))
                    {
                        if (previousIsWhitespace)
                        {
                            continue;
                        }
    
                        previousIsWhitespace = true;
                    }
                    else
                    {
                        previousIsWhitespace = false;
                    }
    
                    newString.Append(value[i]);
                }
    
                return newString.ToString();
            }
        }
    

    它将被用作:

    string testValue = "This contains     too          much  whitespace."
    testValue = testValue.ReduceWhitespace();
    // testValue = "This contains too much whitespace."
    
        8
  •  15
  •   Jan Goyvaerts    16 年前
    myString = Regex.Replace(myString, " {2,}", " ");
    
        9
  •  11
  •   Nolonar    11 年前

    Regex ,下面是一个使用 StringBuilder :

        public static string FilterWhiteSpaces(string input)
        {
            if (input == null)
                return string.Empty;
    
            StringBuilder stringBuilder = new StringBuilder(input.Length);
            for (int i = 0; i < input.Length; i++)
            {
                char c = input[i];
                if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))
                    stringBuilder.Append(c);
            }
            return stringBuilder.ToString();
        }
    

    在我的测试中,与静态编译的Regex相比,使用一组非常大的中小型字符串时,此方法的平均速度要快16倍。与非编译或非静态Regex相比,这应该更快。

    记住,它确实

        10
  •  8
  •   ravish.hacker    9 年前

    你可以简单地在一行解决方案!

    string s = "welcome to  london";
    s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");
    

        11
  •  6
  •   Aleks Andreev Md. Suman Kabir    7 年前

    这是一个较短的版本,只有在只执行一次时才应该使用,因为它创建了 Regex 每次叫它的时候都要上课。

    temp = new Regex(" {2,}").Replace(temp, " "); 
    

    如果你对正则表达式不太熟悉,这里有一个简短的解释:

    {2,} 使regex搜索其前面的字符,并查找2到无限次之间的子字符串。
    这个 .Replace(temp, " ")

    如果您想多次使用它,这里有一个更好的选项,因为它在编译时创建regex IL:

    Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
    temp = singleSpacify.Replace(temp, " ");
    
        12
  •  6
  •   Stephen du Buis    7 年前

    没有Regex,没有Linq。。。删除前导和尾随空格,并将任何嵌入的多个空格段缩减为一个空格

    string myString = "   0 1 2  3   4               5  ";
    myString = string.Join(" ", myString.Split(new char[] { ' ' }, 
    StringSplitOptions.RemoveEmptyEntries));
    

        13
  •  4
  •   Jay Bazuzi Buck Hodges    16 年前

    根据乔尔的说法,我还可以找到其他的答案,希望在我开始的过程中能有所改善:

    你可以这样做 Regex.Replace() :

    string s = Regex.Replace (
        "   1  2    4 5", 
        @"[ ]{2,}", 
        " "
        );
    

    或与 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 (" ");
    
        14
  •  3
  •   Jay Bazuzi Buck Hodges    16 年前

    我刚写了一篇新的 Join

    public static string Join<T>(this IEnumerable<T> source, string separator)
    {
        return string.Join(separator, source.Select(e => e.ToString()).ToArray());
    }
    

    其中一个很酷的地方是,它通过对元素调用ToString()来处理不是字符串的集合。用法仍然相同:

    //...
    
    string s = "     1  2    4 5".Split (
        " ".ToCharArray(), 
        StringSplitOptions.RemoveEmptyEntries
        ).Join (" ");
    
        15
  •  2
  •   Paul Easter    10 年前

    我知道这是相当古老的,但遇到这个,同时试图完成几乎相同的事情。在RegEx Buddy中找到了这个解决方案。此模式将所有双空格替换为单空格,还将修剪前导空格和尾随空格。

    pattern: (?m:^ +| +$|( ){2,})
    replacement: $1
    

    这有点难读,因为我们处理的是空的空间,所以这里再次用“空间”替换为“空间”。

    pattern: (?m:^_+|_+$|(_){2,})  <-- don't use this, just for illustration.
    

    “(?m: “construct启用“多行”选项。我通常喜欢在模式本身中包含任何我可以选择的选项,这样它就更加独立了。

        16
  •  2
  •   The_Black_Smurf Goutham    6 年前

    Nolanar's answer (这是表现最好的答案)提高了10%。

    public static string MergeSpaces(this string str)
    {
    
        if (str == null)
        {
            return null;
        }
        else
        {
            StringBuilder stringBuilder = new StringBuilder(str.Length);
    
            int i = 0;
            foreach (char c in str)
            {
                if (c != ' ' || i == 0 || str[i - 1] != ' ')
                    stringBuilder.Append(c);
                i++;
            }
            return stringBuilder.ToString();
        }
    
    }
    
        17
  •  1
  •   Learner1947    9 年前

    我可以用这个去掉空白

    while word.contains("  ")  //double space
       word = word.Replace("  "," "); //replace double space by single space.
    word = word.trim(); //to remove single whitespces from start & end.
    
        18
  •  1
  •   Ahmed Aljaff    6 年前

    试试这个方法

    private string removeNestedWhitespaces(char[] st)
    {
        StringBuilder sb = new StringBuilder();
        int indx = 0, length = st.Length;
        while (indx < length)
        {
            sb.Append(st[indx]);
            indx++;
            while (indx < length && st[indx] == ' ')
                indx++;
            if(sb.Length > 1  && sb[0] != ' ')
                sb.Append(' ');
        }
        return sb.ToString();
    }
    

    像这样使用:

    string test = removeNestedWhitespaces("1 2 3  4    5".toCharArray());
    
        19
  •  1
  •   Code    5 年前
          // Mysample string
                string str ="hi you           are          a demo";
    
                //Split the words based on white sapce
                var demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
    
                //Join the values back and add a single space in between
                        str = string.Join(" ", demo);
    
    //output: string str ="hi you are a demo";
    
        20
  •  1
  •   Reap    5 年前

    这是一个 Nolonar original answer .

    检查字符是否不只是空格,而是任何空格,请使用以下命令:

    它将用一个空格替换任意多个空白字符。

    public static string FilterWhiteSpaces(string input)
    {
        if (input == null)
            return string.Empty;
    
        var stringBuilder = new StringBuilder(input.Length);
        for (int i = 0; i < input.Length; i++)
        {
            char c = input[i];
            if (i == 0 || !char.IsWhiteSpace(c) || (char.IsWhiteSpace(c) && 
                !char.IsWhiteSpace(strValue[i - 1])))
                stringBuilder.Append(c);
        }
        return stringBuilder.ToString();
    }
    
        21
  •  0
  •   onedaywhen    12 年前

    老斯科尔:

    string oldText = "   1 2  3   4    5     ";
    string newText = oldText
                        .Replace("  ", " " + (char)22 )
                        .Replace( (char)22 + " ", "" )
                        .Replace( (char)22 + "", "" );
    
    Assert.That( newText, Is.EqualTo( " 1 2 3 4 5 " ) );
    
        22
  •  0
  •   Tom Gullen    9 年前

    while (myString.IndexOf("  ", StringComparison.CurrentCulture) != -1)
    {
        myString = myString.Replace("  ", " ");
    }
    

    可以在短字符串上使用,但在具有大量空格的长字符串上会表现糟糕。

        23
  •  0
  •   M.Hassan    6 年前

    使用regex模式

        [ ]+    #only space
    
       var text = Regex.Replace(inputString, @"[ ]+", " ");
    
        24
  •  0
  •   Patrick Artner    6 年前

    混合 StringBuilder Enumerable.Aggregate() 作为字符串的扩展方法:

    using System;
    using System.Linq;
    using System.Text;
    
    public static class StringExtension
    {
        public static string StripSpaces(this string s)
        {
            return s.Aggregate(new StringBuilder(), (acc, c) =>
            {
                if (c != ' ' || acc.Length > 0 && acc[acc.Length-1] != ' ')
                    acc.Append(c);
    
                return acc;
            }).ToString();
        }
    
        public static void Main()
        {
            Console.WriteLine("\"" + StringExtension.StripSpaces("1   Hello       World  2   ") + "\"");
        }
    }
    

    输入:

    "1   Hello       World  2   "
    

    "1 Hello World 2 "