[英]How do I replace multiple spaces with a single space in C#?
如何用 C# 中只有一個空格替換字符串中的多個空格?
例子:
1 2 3 4 5
將是:
1 2 3 4 5
我喜歡使用:
myString = Regex.Replace(myString, @"\s+", " ");
因為它將捕獲任何類型的空格(例如制表符、換行符等)並將它們替換為單個空格。
string sentence = "This is a sentence with multiple spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
string xyz = "1 2 3 4 5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
我認為馬特的答案是最好的,但我認為這不太正確。 如果要替換換行符,必須使用:
myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);
另一種使用 LINQ 的方法:
var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
str = string.Join(" ", list);
即使執行簡單的任務,正則表達式也可能相當慢。 這將創建一個可用於任何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."
它比所有這些都簡單得多:
while(str.Contains(" ")) str = str.Replace(" ", " ");
myString = Regex.Replace(myString, " {2,}", " ");
對於那些不喜歡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 相比,這應該更快。
請記住,它不會刪除開頭或結尾的空格,只有這樣多次出現。
這是一個較短的版本,只有在您只執行一次時才應該使用它,因為它每次調用時都會創建一個Regex
類的新實例。
temp = new Regex(" {2,}").Replace(temp, " ");
如果您不太熟悉正則表達式,這里有一個簡短的解釋:
{2,}
使正則表達式搜索其前面的字符,並查找 2 次和無限次之間的子字符串。
.Replace(temp, " ")
用空格替換字符串 temp 中的所有匹配項。
如果您想多次使用它,這是一個更好的選擇,因為它在編譯時創建正則表達式 IL:
Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");
您可以簡單地在一行解決方案中做到這一點!
string s = "welcome to london";
s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");
如果您願意,您可以選擇其他括號(甚至其他字符)。
沒有正則表達式,沒有 Linq... 刪除前導和尾隨空格,並將任何嵌入的多個空格段減少到一個空格
string myString = " 0 1 2 3 4 5 ";
myString = string.Join(" ", myString.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries));
結果:“0 1 2 3 4 5”
根據喬爾的說法,合並其他答案,並希望隨着我的進步而略有改善:
你可以用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 (" ");
// 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";
我剛剛寫了一個我喜歡的新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 (" ");
許多答案都提供了正確的輸出,但對於那些尋求最佳性能的人來說,我確實將Nolanar 的答案(這是性能的最佳答案)提高了大約 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();
}
}
使用正則表達式
[ ]+ #only space
var text = Regex.Replace(inputString, @"[ ]+", " ");
我知道這已經很老了,但是在嘗試完成幾乎相同的事情時遇到了這個問題。 在 RegEx Buddy 中找到了這個解決方案。 此模式將用單個空格替換所有雙空格,並修剪前導和尾隨空格。
pattern: (?m:^ +| +$|( ){2,})
replacement: $1
由於我們正在處理空白空間,因此閱讀起來有點困難,因此這里再次將“空格”替換為“_”。
pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.
"(?m:" 構造啟用了"多行"選項。我通常喜歡在模式本身中包含我可以使用的任何選項,以便它更加獨立。
我可以用這個刪除空格
while word.contains(" ") //double space
word = word.Replace(" "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.
試試這個方法
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());
不使用正則表達式:
while (myString.IndexOf(" ", StringComparison.CurrentCulture) != -1)
{
myString = myString.Replace(" ", " ");
}
可以在短字符串上使用,但在有很多空格的長字符串上表現不佳。
這是對Nolonar 原始答案的輕微修改。
檢查字符是否不僅僅是一個空格,而是任何空格,使用這個:
它將用一個空格替換任何多個空格字符。
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();
}
老學校:
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 " ) );
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 "
我查看了提議的解決方案,找不到可以處理我的情況可接受的空白字符混合的解決方案,例如:
Regex.Replace(input, @"\\s+", " ")
- 它會吃掉你的換行符,如果它們與空格混合,例如\\n \\n
序列將被替換為
Regex.Replace(source, @"(\\s)\\s+", "$1")
- 它取決於空格的第一個字符,這意味着它可能會再次吃掉你的換行符Regex.Replace(source, @"[ ]{2,}", " ")
- 當混合空格字符時它不會正常工作 - 例如"\\t \\t "
可能並不完美,但對我來說快速解決方案是:
Regex.Replace(input, @"\s+",
(match) => match.Value.IndexOf('\n') > -1 ? "\n" : " ", RegexOptions.Multiline)
想法是 - 換行符勝過空格和制表符。
這不會正確處理 Windows 換行符,但也很容易調整以使用它,不太了解正則表達式 - 可能有可能適合單一模式。
出軌怎么辦?
public static string MinimizeWhiteSpace(
this string _this)
{
if (_this != null)
{
var returned = new StringBuilder();
var inWhiteSpace = false;
var length = _this.Length;
for (int i = 0; i < length; i++)
{
var character = _this[i];
if (char.IsWhiteSpace(character))
{
if (!inWhiteSpace)
{
inWhiteSpace = true;
returned.Append(' ');
}
}
else
{
inWhiteSpace = false;
returned.Append(character);
}
}
return returned.ToString();
}
else
{
return null;
}
}
以下代碼將所有多個空格刪除為一個空格
public string RemoveMultipleSpacesToSingle(string str)
{
string text = str;
do
{
//text = text.Replace(" ", " ");
text = Regex.Replace(text, @"\s+", " ");
} while (text.Contains(" "));
return text;
}
您可以使用RemoveDoubleSpaces() 之類的方法創建 StringsExtensions 文件。
字符串擴展.cs
public static string RemoveDoubleSpaces(this string value)
{
Regex regex = new Regex("[ ]{2,}", RegexOptions.None);
value = regex.Replace(value, " ");
// this removes space at the end of the value (like "demo ")
// and space at the start of the value (like " hi")
value = value.Trim(' ');
return value;
}
然后你可以像這樣使用它:
string stringInput =" hi here is a demo ";
string stringCleaned = stringInput.RemoveDoubleSpaces();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.