Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse every word in a string and capitalize the start of the word

Sample input:

abc def ghi

Sample output:

Cba Fed Ihg

This is my code:

import java.util.Stack;

public class StringRev {
    static String output1 = new String();
    static Stack<Character> stack = new Stack<Character>();
    public static void ReverseString(String input) {
        input = input + " ";
        for (int i = 0; i < input.length(); i++) {
            boolean cap = true;
            if (input.charAt(i) == ' ') {
                while (!stack.isEmpty()) {
                    if (cap) {
                        char c = stack.pop().charValue();
                        c = Character.toUpperCase(c);
                        output1 = output1 + c;
                        cap = false;
                    } else
                        output1 = output1 + stack.pop().charValue();
                }
                output1 += " ";
            } else {
                stack.push(input.charAt(i));
            }
        }
        System.out.print(output1);
    }
}

Any better solutions?

like image 352
rtindru Avatar asked Dec 26 '22 19:12

rtindru


2 Answers

Make use of

StringBuilder#reverse()

Then without adding any third party libraries,

    String originalString = "abc def ghi";
    StringBuilder resultBuilder = new StringBuilder();
    for (String string : originalString.split(" ")) {
        String revStr = new StringBuilder(string).reverse().toString();
        revStr = Character.toUpperCase(revStr.charAt(0))
                + revStr.substring(1);
        resultBuilder.append(revStr).append(" ");
    }
    System.out.println(resultBuilder.toString());  //Cba Fed Ihg 

Have a Demo

like image 152
Suresh Atta Avatar answered Dec 28 '22 11:12

Suresh Atta


You can use the StringBuffer to reverse() a string.

And then use the WordUtils#capitalize(String) method to make first letter of the string capitalized.

String str = "abc def ghi";
StringBuilder sb = new StringBuilder();
for (String s : str.split(" ")) {
    String revStr = new StringBuffer(s).reverse().toString();
    sb.append(WordUtils.capitalize(revStr)).append(" ");
}
String strReversed = sb.toString();
like image 39
Rahul Avatar answered Dec 28 '22 10:12

Rahul