簡體   English   中英

從字符串中刪除字符和空格

[英]Remove character and space from a string

我正在嘗試從另一個字符串中刪除出現在一個字符串上的所有字符。 理想情況下,生成的字符串將不會包含兩個相鄰的空格,至少刪除的字符一定不能替換為空格(或其他任何不可見的字符)。

我想出了以下代碼,但如果這樣做,則會留下某種空格(除了具有多個順序空格,而不是" a " )。 也有刪除方法,但是它需要索引,因此會使解決方案復雜化。

String s1="aeiou";

String s2="This is a test string which could be any text";

Console.WriteLine(s2);
for (int i=0; i<s1.Length; i++)
{
  if(s2.Contains(s1[i]))
  { 
    s2= s2.Replace(s1[i],'\0');
  }
}

Console.WriteLine(s2);

輸出:

在此處輸入圖片說明

預期產量:

這是tst strng whch cld b ny txt

我使用'\\ 0'作為string.Replace()僅期望字符,並且第二個參數的版本為字符串。 string.Empty第一個參數也必須為字符串(這需要轉換-稍后顯示為“變量1”)。

我已經從這些相關的/建議的重復文章中引用了( 從C#字符串刪除字符,從字符串c#中刪除'\\'char ),但是沒有找到完全令我滿意的方法。

變體1 (基於投票最多的答案 。此版本需要將我要替換的每個字符轉換為我不喜歡的字符串:

String s1="aeiou";
String s2="This is a test string which could be any text";

Console.WriteLine(s2);
foreach(var c in s1)
{
   s2 = s2.Replace(c.ToString(), string.Empty);
}
Console.WriteLine(s2);

變體2 - String.JoinString.Splitanswer )。 當我希望避免這種情況時,需要將源替換字符串轉換為數組。

String s1="aeiou";
String s2="This is a test string which could be any text";

s2 = String.Join("", s2.Split(s1.ToCharArray()));

變體3 - Regex.Replaceanswer )-這比變體2還要復雜,因為我需要將替換字符串轉換為正確的正則表達式,可能因為"^!"類的東西而被完全破壞"^!" 作為要替換的字符串(在這種情況下也不需要):

String s1="aeiou";
String s2="This is a test string which could be any text";

s2 = Regex.Replace(s2, "["+s1+"]", String.Empty);
Console.WriteLine(s2);

變體4使用Linq從結果char數組構造字符串( 答案要求在構造字符串之前將結果序列轉換為數組(理想情況下應避免):

String s1="aeiou";
String s2="This is a test string which could be any text";

s2 = new string(s2.Where(c => !s1.Contains(c)).ToArray());
Console.WriteLine(s2);

變體5-使用String.Concatanswer )到目前為止看起來最好,但是使用Linq(我不願意...也許沒有充分的理由在這里使用Linq)

String s1="aeiou";
String s2="This is a test string which could be any text";

s2 = string.Concat(s2.Where(c => !s1.Contains(c)));
Console.WriteLine(s2);

我提出的解決方案都沒有刪除重復的空格 ,所有X版本都確實刪除了字符,但是我的情況有一些問題。 理想的答案不會創建太多額外的字符串,不會產生Linq,也不會產生額外的數組轉換。

假設您要排除字符串中的字符,然后再用單個空格替換多個空格, regex可以分兩步輕松使用regex

string input = "This is a test string which could be any text";
string exclude = "aeiou";

var stripped = Regex.Replace(input, $"[{exclude}]", ""); // exclude chars
var cleaned = Regex.Replace(stripped, "[ ]{2,}", " "); // replace multiple spaces

Console.WriteLine(stripped);
Console.WriteLine(cleaned);

產量

Ths s  tst strng whch cld b ny txt
Ths s tst strng whch cld b ny txt

完整的演示在這里

注意:如果您的字符串可以包含需要在正則表達式中轉義的字符,請使用Regex.Escape ,如以下答案所示- $"[{Regex.Escape(exclude)}]"

在您的情況下,使用StringBuilders2構建結果:

String s1 = "aeiou";
String s2 = "This is a test string which could be any text";

StringBuilder sb = new StringBuilder();

for (int i = 0; i < s2.Length; i++)
{
    // Check if current char is not contained in s1,
    // then add it to sb
    if (!s1.Contains(s2[i]))
    {
        sb.Append(s2[i]);
    }
}

string result = sb.ToString();

編輯:

為了從字符串中刪除空格,您可以執行以下操作:

string result = string.Join(" ", sb.ToString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));

輸出:

這是tst strng whch cld b ny txt

另外,這是LINQ解決方案:

var result = string.Concat(s2.Where(c => !s1.Contains(c)));

同樣,對於這一點,如果要刪除單詞之間的空格(可以為此創建擴展方法):

var raw = string.Concat(s2.Where(c => !s1.Contains(c)));
var result = string.Join(" ", raw.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));

參考: Enumerable.Where方法String.Contains方法String.Concat方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM