Search code examples
c#alphabetical-sort

String Alphabetizer - Not Alphabetizing first word


Newbie here stuck on a small issue. I am just doing a small easy task to work on skills but I can't out this little issue. Essentially I am parsing a sentence string through a method that will take each word apart and alphabetize each word. However, I can't work out why the first word never alphabetizes. Any help is much appreciated.

static string Alphabetize(string word)
{
    char[] a = word.ToCharArray();
    Array.Sort(a);
    return new string(a);
}

static void Scrambler(string sentence)
{
    string tempStore = "";
    List<string> sentenceStore = new List<string>();
    Regex space = new Regex(@"^\s+$");

    // Store each word in a list
    for (int c = 0; c < sentence.Length; c++)
    {
        if (!space.IsMatch(Convert.ToString(sentence[c])))
        {
            tempStore += Convert.ToString(sentence[c]);
            if (sentence.Length - 1 == c)
            {
                sentenceStore.Add(tempStore);
            }
        }
        else
        {
            sentenceStore.Add(tempStore);
            tempStore = "";
        }
    }

    foreach (string s in sentenceStore)
    {   
        Console.Write(Alphabetize(s));
        Console.WriteLine();
    }
}

static void Main(string[] args)
{
    Scrambler("Hello my name is John Smith");
}

Solution

  • It does "alphabetize" (sort) your first word. When "alphabetizeing" with Array.Sort(), it takes Uppercase Letters first in alphabetic order then Lowercase Letters in alphabetic order.

    so "cCbBaA" for example should become "ABCabc"

    or "Smith" for example should become "Shimt"

    and "Hello" will remain "Hello"

    on a side note: you should consider using String.Split()