猿问

我如何使用“String.Empty”功能从文本中删除单词,但在 C# 中一次删除多个不同的单词

是否可以删除“and”、“is”、“and other Words”而不仅仅是“and”

original = original.Replace("and", String.Empty);

我正在尝试创建一个程序,可以检测并通过删除不相关的单词(例如“and”,“is”,“because”等)来压缩文本文件。

string original = "yeet is and this because working is  what help me.";

original = original.Replace("and", String.Empty);
Console.WriteLine(original);
Console.ReadLine();

它不会运行代码,而是只会说“名称可以简化”,如果我执行“and”,“in”,我确实尝试使用或如 || 中那样。


DIEA
浏览 159回答 4
4回答

holdtom

我也要向这一点致敬。我刚刚测试了这两种方法,它们现在可以正常工作(编辑后),无需删除部分单词以及保留重复的单词。由于没有排序,它也保持了单词的顺序。它们还删除了单词之间意外的额外空格。var irrelevantWords = new List<string>{&nbsp; &nbsp; "and", "is", "the", "of"};string original = "yeet is and this because working is&nbsp; what help me.";List<string> result = new List<string>();foreach (string word in original.Split(' ')){&nbsp; &nbsp; if (!word.Equals(string.Empty) && (irrelevantWords.IndexOf(word) == -1))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; result.Add(word);&nbsp; &nbsp; }}return string.Join(" ", result);使用 Linq 可以将循环缩短为单行。return string.Join(" ", original&nbsp; &nbsp; .Split(' ')&nbsp; &nbsp; .ToList()&nbsp; &nbsp; .Where(word => !word.Equals(string.Empty) && (irrelevantWords.IndexOf(word) == -1))));

慕勒3428872

如果你有一堆“不相关”的单词,你可以将它们存储在一个列表中,然后在循环中替换它们:var irrelevantWords = new List<string>{&nbsp; &nbsp; "and", "is", "the", "of"};string original = "yeet is and this because working is&nbsp; what help me.";foreach (var irrelevantWord in irrelevantWords){&nbsp; &nbsp; original = original.Replace(irrelevantWord, string.Empty);}

慕田峪9158850

你有什么理由不能这样做吗?original = original.Replace("and", String.Empty); original = original.Replace("because", String.Empty); original = original.Replace("is", String.Empty);           Console.WriteLine(original); Console.ReadLine();---如果您查看String.Replace 方法,您会发现它一次只能接受 2 个参数,即 char,char 或 string,string。

翻翻过去那场雪

使用String.Replace,我不这么认为。但是,您可以使用“联接”和“拆分”。就像是:var exceptWords = new HashSet<string>{    "and", "is", "the", "of"};string original = "yeet is and this because working is  what help me.";var originalSet = new HashSet<string>(original.Split(' '));originalSet.ExceptWith(exceptWords);var output = String.Join(" ", originalSet);但是,您可以使用“联接”和“拆分”。就像是:var exceptWords = new HashSet<string>{    "and", "is", "the", "of"};string original = "yeet is and this because working is  what help me.";var originalSet = new HashSet<string>(original.Split(' '));originalSet.ExceptWith(exceptWords);var output = String.Join(" ", originalSet);
随时随地看视频慕课网APP
我要回答