4 回答
TA贡献1805条经验 获得超10个赞
我也要向这一点致敬。我刚刚测试了这两种方法,它们现在可以正常工作(编辑后),无需删除部分单词以及保留重复的单词。由于没有排序,它也保持了单词的顺序。它们还删除了单词之间意外的额外空格。
var irrelevantWords = new List<string>
{
"and", "is", "the", "of"
};
string original = "yeet is and this because working is what help me.";
List<string> result = new List<string>();
foreach (string word in original.Split(' '))
{
if (!word.Equals(string.Empty) && (irrelevantWords.IndexOf(word) == -1))
{
result.Add(word);
}
}
return string.Join(" ", result);
使用 Linq 可以将循环缩短为单行。
return string.Join(" ", original
.Split(' ')
.ToList()
.Where(word => !word.Equals(string.Empty) && (irrelevantWords.IndexOf(word) == -1))));
TA贡献1848条经验 获得超6个赞
如果你有一堆“不相关”的单词,你可以将它们存储在一个列表中,然后在循环中替换它们:
var irrelevantWords = new List<string>
{
"and", "is", "the", "of"
};
string original = "yeet is and this because working is what help me.";
foreach (var irrelevantWord in irrelevantWords)
{
original = original.Replace(irrelevantWord, string.Empty);
}
TA贡献1794条经验 获得超7个赞
你有什么理由不能这样做吗?
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。
TA贡献2065条经验 获得超13个赞
使用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);
- 4 回答
- 0 关注
- 145 浏览
添加回答
举报