You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET中从字符串移除指定字符串数组内的词汇?

解决方法

你之前的问题出在对Except方法的使用场景理解错误:字符串的Except方法是针对单个字符进行对比筛选的,不是按完整单词处理,所以根本达不到移除指定词汇的效果。

正确的实现逻辑是按单词拆分、筛选、重新拼接:

  1. 将原句子按空格拆分为单词数组,同时移除拆分后可能产生的空字符串
  2. 用Except筛选出不在排除列表中的单词
  3. 将筛选后的单词重新拼接成完整字符串

完整代码示例:

string[] excludeWords = {"word1","word2","word3","word4","word5"};
string sentence = "word1 word2 word5 marble1";

// 拆分句子为单词数组,移除空项
string[] sentenceWords = sentence.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
// 筛选出不在排除列表的单词
IEnumerable<string> filteredWords = sentenceWords.Except(excludeWords);
// 重新拼接为字符串
string filteredText = string.Join(" ", filteredWords);

TextBox1.Text = filteredText;

如果需要忽略单词的大小写(比如同时移除Word1和word1),可以使用Except的重载方法,指定字符串比较器:

IEnumerable<string> filteredWords = sentenceWords.Except(excludeWords, StringComparer.OrdinalIgnoreCase);

内容的提问来源于stack exchange,提问作者user20465780

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 11:01:00