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
#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);
}
In Java:
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String str = bf.readLine();
String[] l = str.split(” “);
for(int i=l.length-1;i>=0;i–) {
System.out.print(l[i]+” “);
}
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] + " ");
}
Console.Read();
}
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]);
}
}}
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]);
}
}}