【发布时间】:2016-04-12 20:03:22
【问题描述】:
我在 c# 中使用了一个字符串列表,其中包含一个主题列表。
例如艺术、科学、音乐。
然后我让用户输入“我想学习科学和艺术”。
我想将结果存储到一个变量中,但我得到了很多重复项,例如“science, sciencemusic”(这不是错字)。
我认为这是来自 for each 语句的循环。有没有更简单的方法可以做到这一点,或者我的代码有问题吗?我想不通。
这是我的代码:
string input = "I would like to study science and art.";
string result = "";
foreach (string sub in SubjectsClass.SubjectsList)
{
Regex rx = new Regex(sub, RegexOptions.IgnoreCase);
MatchCollection matches = rx.Matches(input);
foreach (Match match in matches)
{
result += match.Value;
}
}
主题类函数“SubjectsList”是从 CSV 文件中读取的,其中只有随机主题的单词:
CSV 文件:
计算 英语 数学 艺术 科学 工程
private list<string> subjects = new list<string>();
//Read data from csv file to list...
public list<string>SubjectsList
{
get { return subjects; }
{
目前我得到的输出是这样的:
"input": "art science",
"Subject": "artscienceartscienceartscience"
如果我改变:
result += match.Value;
到
result += match.Value + " ";
我有很多空间。
编辑:我应该提到,此代码在 WPF c# 按钮按下时运行,然后显示结果。
【问题讨论】:
-
做这个结果 += match.Value + " "';仅当 match.Success 时,如:if (match.Success) { result += match.Value + " "; }
-
您的代码有点不完整,很难重现该行为或跟踪问题。但我可能会检查你的循环——看起来它在同一个地方经过了好几次。您可能还应该查看您的表达式 - 它可能会创建不正确的匹配项(超出您的预期)...
-
你为什么不在你的循环中做一个
if(input.Contains(sub)) result+=sub;? -
我刚刚在输入
"art science"上运行了您的代码并得到了结果"artscience",而不是您在问题中所说的"artscienceartscienceartscience"。您能否确保提供足够的代码,以便我可以复制/粘贴/运行您的代码并获得您得到的结果。我们需要一个minimal reproducible example。