package javareversestring; import java.util.List; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaReverseString { public static void main(String[] args) { String original; Scanner scanner = new Scanner(System.in); System.out.println("Enter a string:"); original = scanner.nextLine(); String reverseString = ""; for(int i=original.length()-1; i>=0; i--){ reverseString= reverseString + original.charAt(i); } System.out.println(reverseString); System.out.println(new StringBuffer(original).reverse().toString()); System.out.println(reverseWords(original)); System.out.println(reverseCharsInWords(original)); } //reverse words static private String reverseWords(String src){ String reversed = ""; Stack<String> stackString = new Stack<>(); StringTokenizer stringTokenizer = new StringTokenizer(src); while(stringTokenizer.hasMoreTokens()){ stackString.push(stringTokenizer.nextToken()); } while(!stackString.empty()){ reversed += stackString.pop() + " "; } return reversed; } //reverse chars in words static private String reverseCharsInWords(String src){ String reversed = ""; List<String> listString = new Stack<>(); StringTokenizer stringTokenizer = new StringTokenizer(src); while(stringTokenizer.hasMoreTokens()){ listString.add(stringTokenizer.nextToken()); } while(!listString.isEmpty()){ String s = listString.remove(0); reversed += new StringBuffer(s).reverse().toString() + " "; } return reversed; } }
Friday, March 27, 2015
Reverse String, reverse words order, reverse chars in words
This example show various methods to reverse chars in String, reverse words order, and reverse chars in words but keep words in order.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment