Reverse a string word by word,(in place)

Write a Program to reverse the words in a string.
Example
Input : Hello! How are you
Output: you are How Hello!

The words are reversed, but the letters are still in order (within the word).
Algorithm:

i)Reverse the whole string.
You will get “uoy era woH !olleH”
ii)Then reverse each word.
Now it will be “you are How Hello!”

```#include<stdio.h>
void reverseString(char *beg,char *end)
{
char temp;
while(beg<end)
{
temp = *beg;
*beg++ = *end;
*end-- = temp;
}
}

void reverseWords(char *str)
{
char *beg = str;
char *end = str;

/*Reverse string word by word*/
while( *end )
{
end++;
if (*end == '\0'||*end == ' ')
{
reverseString(beg, end-1);
beg = end+1;
}
}

/*Reverse the whole string*/
reverseString(str, end-1);
}

/* driver function to test the above function */
int main()
{
char str[] = "Hello! How are you.";
reverseWords(str);
printf("%s",str);
getchar();
return 0;
}
```

Complexity O(l) where l is the length of the string

5 Thoughts on “Reverse a string word by word,(in place)”

1. #include
#include
#include
reverse(char *str,int s,int l)
{
int i,j;
char c;
for(i=s,j=l;i<=j;i++,j–)
{
c=str[i];
str[i]=str[j];
str[j]=c;
}
}
spacereverse(char *str,int n)
{
int i,index;
index=0;
for(i=0;i<n;i++)
{
if(str[i]==' ')
{
reverse(str,index,i-1);
index=i+1;
}
}
reverse(str,index,i-1);
}
int main()
{
char str[100];
gets(str);
reverse(str,0,strlen(str)-1);
//puts(str);
spacereverse(str,strlen(str));
puts(str);
getch();
return(0);
}

2. In Java:

String[] l = str.split(” “);

for(int i=l.length-1;i>=0;i–) {
System.out.print(l[i]+” “);
}

3. Pinkee Goolu on October 8, 2014 at 3:53 pm said:

another way is to make use of string tokenizer
static void Main(string[] args)
{
stringrev();
}

static void stringrev()
{
string str = "Hello how are you";
string[] word = str.Split(' ');

for (int i = word.Length-1;i>=0; i–)
{
Console.Write(word[i] + " ");
}

}

4. donno1 on June 27, 2015 at 6:49 pm said:

public class Inplacereverse {
public static void main(String[] args) {
String str=”This is good chance to Show your hunger”;
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.reverse();
str = sb.toString();
System.out.println(“sb==”+sb);
String [] arr=str.split(” “);

for(int i=0;i<arr.length;i++)
{
StringBuilder sb2 = new StringBuilder();
sb2.append(arr[i]);
sb2.reverse();

arr[i]=sb2.toString();

}
for(int i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
}}

5. Tarun on June 27, 2015 at 6:50 pm said:

public class Inplacereverse {
public static void main(String[] args) {
String str=”This is good chance to Show your hunger”;
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.reverse();
str = sb.toString();
System.out.println(“sb==”+sb);
String [] arr=str.split(” “);

for(int i=0;i<arr.length;i++)
{
StringBuilder sb2 = new StringBuilder();
sb2.append(arr[i]);
sb2.reverse();

arr[i]=sb2.toString();

}
for(int i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
}}