C# 需要有关如何在字母示例之后查找和计算 a - 的帮助:s-

C# need help on how to find and count a - after a letter example: s-

所以我正在尝试计算并显示以特定字母开头然后是 - 例如像 x-ray 这样的单词的单词数。我想出了如何计算以字母 x 开头但似乎无法完成其余部分的单词。当我尝试进行微小的调整时,一切都崩溃了,即只需将 'x' 更改为 "x-" 因为我正在使用 == 并且我无法将字符串与 == 进行比较任何帮助将不胜感激代码是发布...

        int countWordsStartingWithX = 0;
        for (int k = 0; k < phrase.Length; k++)
        {
            if (phrase[k] == 'X' || phrase[k] == 'x')
            {
                if (k == 0)
                    countWordsStartingWithX++;
                else if (phrase[k - 1] == ' ')
                    countWordsStartingWithX++;
            }
        }

        Console.WriteLine("There are {0} words starting with x or X in {1}", countWordsStartingWithX, phrase);

不需要一个字一个字地找。我建议您通过单词和 string.Splitstring.StartsWithLINQ Count 来查找它,像这样的事情就可以了:

string sentence = "this is a test sample! x-ray is here Xsense Xback xbox xmove is all here!";
string[] phrases = sentence.Split(' '); //define this as string[] not char[]
int withx = phrases.Count(x => x.ToLower().StartsWith("x"));
int withx_minus = phrases.Count(x => x.ToLower().StartsWith("x-"));
Console.WriteLine("There are {0} words starting with x or X and {1} words with x- or X- in {2}", withx, withx_minus, sentence);
Console.ReadKey();

您遇到的错误:

operator == can't be applied to operands of type char and string

是因为你的phrasechar[]而不是string[],所以你不能有一个以上的字符:x-是两个字符,不允许,它被认为string