Reverse words in a string

PHOTO EMBED

Tue Feb 08 2022 11:12:51 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #lecture #string #reversewords

// Efficient Approach :
// NOTE : The code doesn’t handle the cases when the string starts with space. 

import java.util.*;
import java.io.*;
  
class GFG { 
       
    static void reverse(char str[],int low, int high)
    {
        while(low<=high)
        {
            //swap
            char temp=str[low];
            str[low]=str[high];
            str[high]=temp;

            low++;
            high--;
        }
    }

    static void reverseWords(char str[],int n){
    int start=0;
    for(int end=0;end<n;end++){
        if(str[end]==' '){
            reverse(str,start,end-1);
            start=end+1;
        }
    }
    reverse(str,start,n-1);
    reverse(str,0,n-1);
    }
  
    public static void main(String args[]) 
    {   String s = "Welcome to Gfg";int n=s.length();
        char[] str = s.toCharArray();
        System.out.println("After reversing words in the string:");
        reverseWords(str,n);
        System.out.println(str);  
    } 
} 
content_copyCOPY