2

Trying to learn C and so I want to reverse each word in string. "Hello World" to "olleH dlroW" This is what I have so far.

int main()
{
    char str[100];
    int i;
    printf("Enter string:");
    fgets(str,sizeof(str),stdin);

    for (i = 0; i <= strlen(str); i++)
    {
        if (str[i] == ' ')
        {
            // Here the space and how should I switch words now?
        }
    }

    return 0;
}

Should I do something like this:

temp = str[i]; j = str[i-1];

and then switch places? str[i]=j; and j=temp; I am stuck at this point here!

MeChris
  • 717
  • 1
  • 7
  • 11
  • Possible duplicate of [Having trouble writing program to reverse words in string in C](http://stackoverflow.com/questions/29243374/having-trouble-writing-program-to-reverse-words-in-string-in-c) – owacoder Dec 02 '15 at 16:37

2 Answers2

5

I won't give away the answer because this seems like a homework problem and is a great opportunity to learn, but here is a hint:

Think about how you could programatically reference the 'opposite' of each letter in the word. So str[0] and str[strlen(str)], and so on. That should help you, but feel free to probe with further questions.

Jaron Thatcher
  • 814
  • 2
  • 9
  • 24
0

Try this...

private void Button1_Click(object sender, EventArgs e)
{
    const string targetWords = "Hello World";
    int count = targetWords.Length;
    string result = null;
    string chr = null;

    while (!(count == 0)) {
        chr = targetWords.Substring((count - 1), 1);
        result += chr;
        count -= 1;
    }
    Debug.WriteLine(result);

}
Rose
  • 641
  • 7
  • 17