Java String Methods Programs

To Print words of a string in reverse order

 public static void main(String[] args)
    {
        String str = "Naveen joshuva";
 
        System.out.print(wordReverse(str));
    }
    
    
   public static String wordReverse(String str)
    {
        int i = str.length() - 1;
        int start=i+1;
       int  end = i + 1;
        String result = "";
 
        while (i >= 0) {
            if (str.charAt(i) == ' ') {
                start = i + 1;
                while (start != end)
                    result += str.charAt(start++);
 
                result += ' ';
 
                end = i;
            }
            i--;
        }
 
        start = 0;
        while (start != end)
            result += str.charAt(start++);
 
        return result;
    }
    

Output:

joshuva Naveen

I got this program from Geeksforgeeks https://www.geeksforgeeks.org/print-words-string-reverse-order/

Now I have a name which is reversed I have to print that like below:

What I tried look into below program:

public static void main(String[] args) {
		// TODO Auto-generated method stub
		Reverseword rw=new Reverseword();
       String str="avuhsoj neevan";
       String out= 	rw.rword(str);
      System.out.println(out);
	 String backword=rw.Lastword(out);
	 System.out.println(backword);
	}



	private String Lastword(String last) {
		// TODO Auto-generated method stub
		 char[] l = last.toCharArray();
		 int begin=8;
		    int end=l.length-1;
		    char temp;
		    while(end>begin){
		        temp = l[begin];
		        l[begin]=l[end];
		        l[end] = temp;
		        end--;
		        begin++;
		    }
		    return new String(l);
		    
	}

private String rword(String input) {
		// TODO Auto-generated method stub
		 char[] in = input.toCharArray();
		 int begin=0;
		    int end=in.length-7;
		    char temp;
		    while(end>begin){
		        temp = in[begin];
		        in[begin]=in[end];
		        in[end] = temp;
		        end--;
		        begin++;
		        
		    }
		    return new String(in);
		}

	
}



Output:

joshuvaneevan
joshuvanaveen

Leave a comment

Design a site like this with WordPress.com
Get started