我有一個字符串,其間有空白字符(\t
,\n
或\n
或空格)的未知組合。例如:修整字符串中的空白字符
string str = "Hello \t\t \n \t \t World! \tPlease Help.";
我想用一個空格來代替內空白字符每個序列:
string str = "Hello World! Please Help.";
是否.NET提供了一個內置的方式做到這一點?如果沒有,我怎麼能通過C#做到這一點?
我有一個字符串,其間有空白字符(\t
,\n
或\n
或空格)的未知組合。例如:修整字符串中的空白字符
string str = "Hello \t\t \n \t \t World! \tPlease Help.";
我想用一個空格來代替內空白字符每個序列:
string str = "Hello World! Please Help.";
是否.NET提供了一個內置的方式做到這一點?如果沒有,我怎麼能通過C#做到這一點?
嘗試使用以下正則表達式替換
string original = ...;
string replaced = Regex.Replace(original, @"\s+", " ");
這用一個空格替換每個組的空白字符(\s
)。您可以在這裏找到其他有用的字符組
using System.Text.RegularExpressions;
newString = Regex.Replace(oldString, @"\s+", " ");
字符串修剪= Regex.Replace(原件,@ 「\ S +」,「「);
沒有達到這個內置的方法,但是你可以使用正則表達式:
string result = Regex.Replace(str, @"\s+", " ");
我用稍微不同的方法。有點羅嗦(目前在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`[email protected]#$%^&*()_+[]\{}|;':,./<>?" + "\"";
Assert.AreEqual(@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`[email protected]#$%^&*()_+[]\{}|;':,./<>?" + "\"", testObj.RemoveCategories(Strings.WhiteSpaceCategories()));
}
你可以嘗試更快的替代方案,而無需使用正則表達式:要做到這一點(行終止,標籤將被處理爲好)
string replaced = String.Join(" ", str.Split(
new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));
您能否提供證據證明您的非正則表達式方法比提供的基於正則表達式的答案更快? – DavidRR 2016-05-10 14:42:06
最快的和通用的方式。 Regex強大的工具並不需要解決這個問題,但Regex可以降低性能。
String
.Join
(" ",
new string
(stringToRemoveWhiteSpaces
.Select
(
c => char.IsWhiteSpace(c) ? ' ' : c
)
.ToArray<char>()
)
.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
)
避免代碼只有答案 – 2017-07-24 12:41:34
'@「\ s {2,}」'可能會更有效一些。 – 2012-03-03 00:56:30
@ OlivierJacot-Descombes爲什麼會更有效率(真正好奇) – JaredPar 2012-03-03 00:57:25
因爲它不需要用另一個單獨的空格替換所有單個空格。但它不會用''「'替換'\ t'。 – 2012-03-03 01:00:53