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

15,371

Solution 1

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

Solution 2

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();

Solution 3

1) Reverse the String with this

StringBuffer a = new StringBuffer("Java");
a.reverse();

2) To make First letter capital use StringUtils class in apache commons lang package org.apache.commons.lang.StringUtils

It makes first letter capital

capitalise(String);

Hope it helps.

Solution 4

public static String reverseString(final String input){
    if(null == input || isEmpty(input))
        return "";

    String result = "";
    String[] items = input.split(" ");

    for(int i = 0; i < items.length; i++){
        result += new StringBuffer(items[i]).reverse().toString();
    }

    return result.substring(0,1).toupperCase() + result.substring(1);
}

Solution 5

Edited

Reverse the string first and make the first character to uppercase

String string="hello jump";
StringTokenizer str = new StringTokenizer(string," ") ;
String finalString ;

while (str.hasMoreTokens()) {
   String input = str.nextToken() ;
   String reverse = new StringBuffer(input).reverse().toString();
   System.out.println(reverse);

   String output = reverse .substring(0, 1).toUpperCase() + reverse .substring(1);
   finalString=finalString+" "+output ;
}

System.out.println(finalString);
Share:
15,371
rtindru
Author by

rtindru

Python! Javaaa! ASP.NET Android! Web Dev! Django! HTML5! CSS3! JavaScript!

Updated on June 04, 2022

Comments

  • rtindru
    rtindru almost 2 years

    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?

    • SpringLearner
      SpringLearner over 10 years
      I think this question belows to codereview.stackexchange.com
    • rtindru
      rtindru over 10 years
      @javaBeginner Should I ask it there as well or can I move it to codeReview. Also Is this a good implementation?
    • newuser
      newuser over 10 years
      Don't use String to concat the results. Use StringBuilder to append the result values. Because String is immutable. Remove the String variable output1 and create a StringBuilder with in the reverseMethod
  • rtindru
    rtindru over 10 years
    I think you didn't follow completely. Its not supposed to do abc to Cba. Rather its gotta do abc def to Cba Fed
  • Arun
    Arun over 10 years
    Then you can tokenize the whole word and apply this above logic to each tokens.
  • Arun
    Arun over 10 years
    Please mark my answer as correct one, if it is useful and simple to your requirement
  • B-Y
    B-Y over 7 years
    stdin is 3 line input, for example, input = "2", "dog", "Cat", and it requires stdout, output = "God", "TaC". How to do Scanner, do I need to use a list? Thank you so much!