Q:

How to Reverse a String in Java Word by Word

0

In this section, we reverse a string in Java word by word.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Example 1: Reverse a string word by word using recursion

import java.util.Scanner;  
public class ReverseStringExample1   
{  
public static void main(String[] args)   
{  
String str;  
System.out.println("Enter a string: ");  
Scanner scanner = new Scanner(System.in);  
str = scanner.nextLine();  
scanner.close();                                //closes the input stream  
String reversed = reverseString(str);  
System.out.println("The reversed string is: " + reversed);  
}  
public static String reverseString(String s)  
{  
if (s.isEmpty())                            //checks the string if empty  
return s;  
return reverseString(s.substring(1)) + s.charAt(0);                     //recursively called function  
}  
}  

Output:

 

Example 2: Reverse a string word by word by using for loop

import java.util.*;  
public class ReverseStringDemo  
{  
public static void main(String[] arg)  
{  
ReverseStringDemo rs=new ReverseStringDemo();  
Scanner sc=new Scanner(System.in);  
System.out.print("Enter a string: ");  
String  str=sc.nextLine();    
System.out.println("Reverse of a String  is : "+rs.reversestr(str));          //called method  
}  
//reverse string method  
static String reversestr(String s)  
{  
String r="";  
for(int i=s.length();i>0;--i)        //execute until condition i>0 becomes false  
{  
r=r+(s.charAt(i-1));   
}  
return r;  
}  
}  

Output:

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now