Search code examples
c#startswith

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


So I'm trying to count and display the count of words that start with a specific letter and then a - for example words like x-ray. I figured out how to count words that just start with the letter x but can't seem to get it the rest of the way. When I try to make minor tweaks everything breaks down i.e. simply change the 'x' to "x-" as I'm using == and I can't compare strings with == any help would be much appreciated code is posted...

        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);

Solution

  • You do not need to find it character by character. I recommend you to find it by words and by string.Split, string.StartsWith, and LINQ Count, something like this will do:

    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();
    

    The error you are getting:

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

    is because your phrase is char[] not string[], thus you cannot have more than one char: x- are two chars, not allowed, it is considered a string