C# 与字符串比较但没有效果
我有一个终端列表:a,b,c,d 我有一部像这样的作品C# 与字符串比较但没有效果,c#,string,C#,String,我有一个终端列表:a,b,c,d 我有一部像这样的作品 A > aA | cC |a 我试图检查生产a的一部分是否是终端,或者该部分是否存在于终端列表中。问题是,当我比较这两部分时,结果总是错误的。我试过使用“Equals”、“Contains”和“==”,结果是一样的,我不知道为什么 我的代码从中分割生产并比较两个部分: foreach (Production production in productions) { Stri
A > aA | cC |a
我试图检查生产a的一部分是否是终端,或者该部分是否存在于终端列表中。问题是,当我比较这两部分时,结果总是错误的。我试过使用“Equals”、“Contains”和“==”,结果是一样的,我不知道为什么
我的代码从中分割生产并比较两个部分:
foreach (Production production in productions)
{
String prod = production.ToString();
String[] right = prod.Trim().Split('>');
String justRightPart = right[1];
String[] separate = justRightPart.Trim().Split('|');
Boolean ok = true;
foreach (String s in separate)
{
foreach(string terminal in terminals)
{
Console.WriteLine("Terminal: " + terminal + " string part is " +s);
Boolean bool = terminal.Contains(s) || (terminal == s);
Console.WriteLine("bool : " + bool);
}
}
}
即使上面说:
Terminal a string part is a
为什么不平等?
有什么建议吗?在
s
中可能有不在终端中的空白,反之亦然。尝试在字符串打印周围添加单引号,例如:
Console.WriteLine("Terminal: '" + terminal + "' string part is '" + s + "'");
如果使用位置参数重写打印,可能会更清晰,例如:
Console.WriteLine("Terminal: '{0}' string part is '{1}'", terminal, s);
我建议使用Linq,例如
结果是
aA is NOT a term
cC is NOT a term
a is a term
应该使用Equals()方法比较字符串。我不相信这段代码正在编译<代码>布尔布尔布尔布尔=终端。包含(s)| |(终端==s)
=>bool
是C#保留的关键字,不能用作标识符。给定该字符串输入,separate
的内容将是{“aA”、“cC”、“a”}
。(注意空格)我是这样写的,但文件中没有空格@Abion47I建议编辑您的问题,删除“production”和“terminal”这两个词,因为它们与问题并不相关-您只是在处理string
s,所以将其设为关于string
s的问题,我在字符串中有空格。但是如何删除它,因为在字符串中,我的文件中有部分产品没有空间?@Adiiia
var report = source
.Substring(source.IndexOf('>') + 1)
.Split('|')
.Select(part => part.Trim())
.Select(part => $"{part,4} is {(terminals.Contains(part) ? "a term" : "NOT a term")}");
Console.Write(string.Join(Environment.NewLine, report));
aA is NOT a term
cC is NOT a term
a is a term