xxxxxxxxxx
To reverse a word
- Put all the letters in a stack and pop them out.
Because of the LIFO order of stack, you will get the letters in
reverse order.
Using 'StringTokenizer' class in JAVA
xxxxxxxxxx
/*
Input : "hellow how are you?"
Output : wolleh woh era ?uoy
*/
public class Main {
// function to reverse a string
static String revString(String str){
String reversedString = "";
int i = str.length()-1;
while(i >= 0){
reversedString += str.charAt(i);
i--;
}
return reversedString;
}
public static void main(String args){
Scanner scn = new Scanner(System.in); // input
System.out.print("Enter a sentence : ");
String sentence = scn.nextLine(); // "Hello how are you?"
StringTokenizer tokenObj = new StringTokenizer(sentence, " ");
while(tokenObj.hasMoreTokens()){// loop while tokenObj is not empty
String word = tokenObj.nextToken();// fetch next token from tokenObj
String reveredstring = revString(word);
System.out.print(reveredstring + " ");
}
}
}
xxxxxxxxxx
// Java Program to reverse a String
// without using inbuilt String function
import java.util.regex.Pattern;
public class Exp {
// Method to reverse words of a String
static String reverseWords(String str)
{
// Specifying the pattern to be searched
Pattern pattern = Pattern.compile("\\s");
// splitting String str with a pattern
// (i.e )splitting the string whenever their
// is whitespace and store in temp array.
String[] temp = pattern.split(str);
String result = "";
// Iterate over the temp array and store
// the string in reverse order.
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
// Driver methods to test above method
public static void main(String[] args)
{
String s1 = "Welcome to geeksforgeeks";
System.out.println(reverseWords(s1));
String s2 = "I love Java Programming";
System.out.println(reverseWords(s2));
}
}