Reverse words programming exercise.

Do you know what is reverse psychology ? No ? Well is like this:


Write a function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.
By the way this function is not to be used on the local newspaper!

Example:
"Hello World!" ==> "olleH !dlroW"

Scroll down for the solution of this awesome programming exercise

    public static string ReverseWords(string str)
    {
    //as always we need some place to store the result
        string r = "";
    //We are going to split the input string to words
    //we have space between words. Se can use that
    //as a separator.
    //The String.Split method creates an array of substrings
//by splitting the input string based on one or more delimiters.
    //we using space ' ' but any char can be used.
        string[] words = str.Split(' ');

    //List is a special data type. Like array but more cool
    //we may add and subtract items, and its very nice to use
    //when you don't know how big of an array you need.
//So we shall create a list of type string and name it rwords
        List<string> rwords = new List<string>();

    //now lets go through each word 
    //and read it backwards
    //we are going to use for loop for that
    //after we make the word we will add it to our list

        foreach (var item in words)
        {
     //the sb variable will be used to store the reversed
     //characters.
            string sb = "";
            for (int i = item.Length-1; i >= 0; i--)
            {
                sb += item[i];                   
            }
//no we well add the reversed word plus one space to the list
            rwords.Add(sb+" ");
        }
    //good we have all the reversed words in our list
    //now we need to write them to a string
        foreach (var item in rwords)
        {
            r += item;
        }
    //since we added one space after each word 
    //we now have an empty space in the end of our 
    //string. We don't need it so we are going 
    //to remove it, and return the result
        return r.Remove(r.Length - 1);
    }