当 if 语句检查单词是否包含字母 "e" 时,为什么我得到 "Operator "==" cannot be applied to operands of type "char" and "string""?

Why do I get "Operator "==" cannot be applied to operands of type "char" and "string"" when if statement check whether word contains letter "e"?

在这个程序中,我想加载一个包含单词的文本文件。然后我继续检查每个单词是否包含字母 "e"。如果是这样,我将字母 "e" 替换为 3,否则我不更改字母。然后,我继续用修改后的单词写一个新文件。

我的问题是,在 'if' 条件检查中,我得到 "Operator "==“无法应用于 "char" 和 "string" 类型的操作数”。我想,也许我无法对 char 和子字符串数字执行“==”操作。那么,我将如何解决这个问题。谢谢!

public static void Main (string[] args)
    {
        System.Console.WriteLine ("Please enter location of the text file to leet: ");

        string myFirstFilePath = Console.ReadLine ();
        string[] firstFile = System.IO.File.ReadAllLines (myFirstFilePath);

        int wordCount = 0;
        ArrayList mixedList = new ArrayList();

        System.Console.WriteLine ("Please enter location of where you would like the new text file to be saved: ");
        string newFileDestination = Console.ReadLine ();

        TextWriter writeToNewFile = new StreamWriter (newFileDestination);
        foreach (string one in firstFile) {
            string word;
            for (int i = 0; i <= one.Length; i++) {
                if (one[i] == "e") {
                    word = word + "3";
                } else {
                    word = word + word.Substring(i);
                    writeToNewFile.WriteLine (one);
                    wordCount++;
                }
            }
        }
        writeToNewFile.Close ();
        Console.WriteLine (wordCount);
        Console.WriteLine ("Press any key to exit.");
        System.Console.ReadKey ();
     }

只需将 one[i] == "e" 替换为 one[i] == 'e'

使用双引号调用 string 类型,而使用单引号调用 char 类型


此外,您声明 string word; 并使用它 (word = word + "3") 而无需分配它。我建议分配它以避免潜在的副作用:string word = "";

您需要将 "e" 更改为单引号 'e'。单引号用于表示一个字符,而双引号表示一个字符串。

例如来自:

if (one[i] == "e")

至:

if (one[i] == 'e')

错误的直接原因是

  "e" - string
  'e' - char (note single quotes)

并且由于 one[i] returns char,解决方案是

  if (one[i] == 'e') 

字符串是角色的数组。要比较 char 数据类型,您应该将它与字符串的特定元素(即单个字符)而不是整个字符串进行比较。

作为

if (one[i] == 'e') \ not like, if (one[i] == "e")