Question

I am working on a small project which is in C# where I want to find and count the latter pairs which comes in alphabetical order by ignoring spaces and special characters. e.g.

This is a absolutely easy.

Here my output should be

hi 1
ab 1

I refereed This post but not getting exact idea for pair latter count.

Was it helpful?

Solution 2

First, I would normalize the string to reduce confusion from special characters like this:

string str = "This is a absolutely easy.";
Regex rgx = new Regex("[^a-zA-Z]");
str = rgx.Replace(str, "");
str = str.ToLower();

Then, I would loop over all of the characters in the string and see if their neighbor is the next letter in the alphabet.

Dictionary<string, int> counts = new Dictionary<string, int>();
for (int i = 0; i < str.Length - 1; i++)
{
    if (str[i+1] == (char)(str[i]+1))
    {
        string index = "" + str[i] + str[i+1];
        if (!counts.ContainsKey(index))
            counts.Add(index, 0);
        counts[index]++;
    }
}

Printing the counts from there is pretty straightforward.

foreach (string s in counts.Keys)
{
    Console.WriteLine(s + " " + counts[s]);
}

OTHER TIPS

First I remove the spaces and special characters as you specified by simply going though the string and checking whether the current character is a letter:

    private static string GetLetters(string s)
    {
        string newString = "";

        foreach (var item in s)
        {
            if (char.IsLetter(item))
            {
                newString += item;
            }
        }

        return newString;
    }

Than I wrote a method which checks if the next letter is in alphabetical order using simple logic. I lower the character's case and check if the current character's ASCII code + 1 is equal to the next one's. If it is, of course they are the same:

    private static string[] GetLetterPairsInAlphabeticalOrder(string s)
    {
        List<string> pairs = new List<string>();

        for (int i = 0; i < s.Length - 1; i++)
        {
            if (char.ToLower(s[i]) + 1 == char.ToLower(s[i + 1]))
            {
                pairs.Add(s[i].ToString() + s[i+1].ToString());
            }
        }

        return pairs.ToArray();
    }

Here is how the main method will look like:

static void Main()
{
    string s = "This is a absolutely easy.";

    s = GetLetters(s);

    string[] pairOfLetters = GetLetterPairsInAlphabeticalOrder(s);

    foreach (var item in arr)
    {
        Console.WriteLine(item);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top