Q:

Reverse the words in a string without using builtin functions like split and substring in C#

I wrote the following:
    class Program
    {
    public static void Main(string[] args)
    {

        string name = "Hello World"

        StringBuilder builder = new StringBuilder();
        for (int i = name.Length - 1; i >= 0; i--)
        {
            builder.Append(name[i]);
        }
        string newName =builder.ToString();

        Console.WriteLine(newName);

    }
}

I am getting "dlrow olleh " as output. I want "World Hello ". 

A:

I wrote a quick solution which uses 2 loops.
The first loop is iterating over the string from left to right.
When it encounters a whitespace (which delimits a word) the second loop starts.
The second loop is looping through the word from right to left. The second loop can not go from left to right because we have no idea where the word will begin (unless we would remember where we met the previous whitespace). Hence the second loop iterates from right to left through the string until it encounters a whitespace (beginning of the word), or until the index becomes 0 (which is a corner case). The same corner case can be observed in the first loop.
Here it is :
String name = "Hello World";
StringBuilder builder = new StringBuilder();

for (int i = 0; i < name.length(); i++)
{
    char tmp = name.charAt(i);
    if(tmp == ' ' || i == name.length() - 1) {
        // Found a whitespace, what is preceding must be a word
        builder.insert(0,  ' ');
        for(int j = i - 1; j >= 0; j--) {
            if(i == name.length() - 1 && j == i - 1) {
                // Exceptional case (necessary because after the last word there is no whitespace)
                builder.insert(0, name.charAt(i));
            } 

            char curr = name.charAt(j);

            if(curr == ' ') {
                // We passed the beginning of the word
                break;
            }
            else if(j == 0) {
                builder.insert(0,  curr);
                break;
            }

            //builder.append(curr);
            builder.insert(0, curr);
        }
    }
}

String newName = builder.toString();
System.out.println(newName);

Note that this is java code but it should be straightforward to translate it to C#.

