1

我有字符串 text="camel",然后我想检查文本是否包含字母“m”,所以我遍历它并使用以下方法检查它:

if (text[i].Equals("m"))

但这永远不会让我回归真实......为什么?

4

5 回答 5

3

由于您正在将字符与字符串进行比较,因此这是行不通的。这是有关字符串比较的更多信息

在这种情况下,您应该使用

if(text.Contains("m"))
于 2013-02-06T20:21:13.797 回答
2

正如@MattGreer 所提到的,您目前正在比较一个字符和一个字符串。这是因为您为文字选择了分隔符,并且因为text[i]从字符串返回字符而不是该字符串的子字符串。

请注意使用字符串文字分隔符(引号)和字符文字分隔符(撇号)之间的区别:

if (text[i].Equals('m'))

此外,正如其他人所说,除非出于某种原因您想遍历每个字符,否则String.Contains()似乎可以达到预期目的。

于 2013-02-06T20:26:52.767 回答
0

You need to find all occurences of a letter in a text as I understand it:

string text = "camel";
string lookup = "M";
int index = 0;
while ( (index = text.IndexOf(lookup, index, StringComparison.OrdinalIgnoreCase) != -1)
{
   // You have found what you looked for at position "index".

}

I don't think that you get it any faster than this.

Good luck with your quest.

于 2013-02-06T20:38:53.300 回答
0

Kyle C 已经给了你答案,所以这就是你完成整个过程的方式,我将winforms以此为例:

private void button1_Click(object sender, EventArgs e)
{
    string text = "camel";

    if (text.Contains("m") || text.Contains("M"))//also checks for capital M
    {
        MessageBox.Show("True");
    }
}
于 2013-02-07T02:21:03.560 回答
-2

无奇迹

利用Contains

您是在问“camel”是否等同于“m” - 它不是。

“骆驼”包含“m”。

于 2013-02-06T20:22:32.290 回答