【问题标题】:Remove character and space from a string从字符串中删除字符和空格
【发布时间】:2019-01-31 05:11:00
【问题描述】:

我正在尝试从另一个字符串中删除出现在一个字符串上的所有字符。理想情况下,生成的字符串不会包含两个相邻的空格,至少删除的字符不能替换为空格(或任何其他不可见字符)。

我想出了以下代码,但如果这样做会留下某种空格(除了有多个连续空格而不是 " 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);

输出:

预期输出:

Ths s tst strng whch cld b ny txt

我使用 '\0' 因为 string.Replace() 只需要字符,并且对于第二个参数为 string.Empty 的版本,第一个参数也必须是字符串(需要转换 - 稍后显示为“变体 1”)。

我已经参考了这些相关/建议的重复帖子(Remove characters from C# string、Remove '\' char from string c#),但没有找到任何让我完全满意的方法。

变体 1(基于投票最多的answer。此版本需要将我要替换的每个字符转换为我不喜欢的字符串:

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.Join 和 String.Split (answer)。当我想避免这种情况时,需要将我的源替换字符串转换为数组。

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

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

变体 3 - Regex.Replace (answer) - 这比变体 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 数组构造字符串(answer 需要在构造字符串之前将结果序列转换为数组(最好避免这种情况):

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 - 使用到目前为止看起来最好但使用 Linq 的 String.Concat (answer)(我不喜欢......也可能没有充分的理由担心在这里使用 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);

我没有提出remove duplicate spaces 的解决方案,所有变体 X 版本都可以很好地删除字符,但对于我的情况有一些问题。理想的答案不会创建太多额外的字符串,没有 Linq 也不会额外转换为数组。

【问题讨论】:

  • 您能否澄清"X a i Z" 输入的结果?到目前为止,我认为常规 Remove characters 是很好的重复,也取决于所需的输出(即,如果你想要 "X Z" 作为结果)那么这是不同的问题。
  • 这很不幸。我认为该问题的 10 多个答案几乎涵盖了从字符串中删除字符的所有明智方法......其中一些已经在此处提供作为答案(但现在很明显,当前的答案都不起作用,因为您已经尝试过它们)。我建议编辑帖子以显示您尝试过的所有变体(显然“我不知道如何将字符转换为字符串”,这是您最后一次编辑节目,这不是拒绝建议的好理由,而是否决的潜在原因由于缺乏经过验证的研究)
  • @AlexeiLevenkov ,我已经更新了问题,以便更清楚地了解我提到的帖子。对于回答问题的人来说,对问题本身有先验知识也很重要(就像你不知道如何将字符转换为字符串一样)..如果没有,那么他们最终也会在这里寻找答案..因此解决方案将受到限制。
  • Bhawna - 我已经用你尝试过的变体更新了帖子,并添加了它们不起作用的解释。如果您愿意,请随意改进(或只是恢复)。 (感谢您指出我缺乏将字符转换为字符串的知识......我会在某处阅读)

标签: c#


【解决方案1】:

假设您想排除字符串中的字符,然后将多个空格替换为单个空格,您可以分两步轻松使用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

Full Demo Here

注意:如果您的字符串可以包含需要在正则表达式中转义的字符,请使用Regex.Escape,如下所示answer - $"[{Regex.Escape(exclude)}]"。

【讨论】:

  • 我添加了关于转义正则表达式的评论以与我对问题的编辑保持一致。如果您不喜欢它,请随时恢复。
  • @AlexeiLevenkov 是的,我看到了,感谢您的编辑:)
【解决方案2】:

根据您的情况使用StringBuilder,从s2 构建您的结果:

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));

输出:

Ths s 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 Method、String.Contains Method、String.Concat Method

【讨论】:

  • 这会在 s 和 tst 之间留下额外的空间,因此不能标记为解决方案:“Ths s tst strng whch cld b ny txt”
猜你喜欢
  • 2011-09-21
  • 2021-10-16
  • 2014-08-17
  • 2021-01-27
  • 2021-04-23
  • 2014-05-20
  • 2017-11-20
相关资源
最近更新 更多