从字符串中删除空格字符

4

我有一个字符串,其中单词之间有未知组合的空格字符(\t, \n或空格)。例如:

string str = "Hello \t\t  \n \t    \t World! \tPlease Help.";

我想把每个内部空格字符序列替换为一个空格:
string str = "Hello World! Please Help.";

.NET提供内置方法来执行此操作吗?如果没有,我该如何使用C#执行此操作?

7个回答

5
using System.Text.RegularExpressions;

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

4

@"\s{2,}" 可以更有效率一些。 - Olivier Jacot-Descombes
@OlivierJacot-Descombes 为什么这样会更有效率呢?(真心好奇) - JaredPar
因为它不必将所有单个空格替换为另一个单个空格。但是它不会将\t替换为" " - Olivier Jacot-Descombes
@OlivierJacot-Descombes 我认为必须替换\t以保持OP所概述的语义。虽然不是100%清楚,但这就是我的理解。 - JaredPar
1
是的,这样做可以 @"\s{2,}|\t|\n"。然而,这可能并不值得复杂化。 - Olivier Jacot-Descombes

1
我使用了稍微不同的方法。它比较冗长(目前是VB),但它允许我轻松地进行各种排除,例如符号、标点或类别的组合。它还使我不必学习正则表达式。
Imports System.Runtime.CompilerServices
Imports System.Globalization
Imports System.Text

Public Module StringExclusions

        <Extension()> Public Function CharsToString(ByVal val As IEnumerable(Of Char)) As String
            Dim bldr As New StringBuilder()
            bldr.Append(val.ToArray)
            Return bldr.ToString()
        End Function

        <Extension()> Public Function RemoveCategories(ByVal val As String, ByVal categories As IEnumerable(Of UnicodeCategory)) As String
            Return (From chr As Char In val.ToCharArray Where Not categories.Contains(Char.GetUnicodeCategory(chr))).CharsToString
        End Function

        Public Function WhiteSpaceCategories() As IEnumerable(Of UnicodeCategory)
            Return New List(Of UnicodeCategory) From {UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.Control}
        End Function
        '...Other commonly used categories removed for brevity.
    End Module

还有一些测试。

   [TestMethod]
    public void RemoveCharacters()
    {
        String testObj = "a \a b \b c \f d \n e \r f \t g \v h";
        Assert.AreEqual(@"abcdefgh", testObj.RemoveCategories(Strings.WhiteSpaceCategories()));
    }

    [TestMethod]
    public void KeepValidCharacters()
    {
        String testObj = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`12334567890-=~!@#$%^&*()_+[]\{}|;':,./<>?"  + "\"";
        Assert.AreEqual(@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`12334567890-=~!@#$%^&*()_+[]\{}|;':,./<>?" + "\"", testObj.RemoveCategories(Strings.WhiteSpaceCategories()));
    }

1

1

没有内置的方法可以实现这一点,但是您可以使用正则表达式:

string result = Regex.Replace(str, @"\s+", " ");

0

您可以尝试一种不使用正则表达式的更快速的替代方法:

string replaced = String.Join(" ", str.Split(
   new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));

你能提供证据表明你的非正则表达式方法比提供的基于正则表达式的答案更快吗? - DavidRR

-1

最快且通用的方法是这样做(行终止符、制表符也将被处理)。不一定需要正则表达式强大的功能来解决这个问题,但正则表达式可能会降低性能。

String  
.Join
(" ",     
  new string  
  (stringToRemoveWhiteSpaces
      .Select
      (
         c => char.IsWhiteSpace(c) ? ' ' : c
      )
      .ToArray<char>()
  )
  .Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接