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?
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With