If we need to reverse each word in a sentence, we can use the split feature in String to first get each word from the string. Later on that word, we can perform the reverse operation.
This question is asked a lot of time at beginner-level automation interviews.
So here are the steps:
1. First split the sentence using a split feature of string. It will return an array of strings.
2. Create a StringBuilder object.
2. Now use a for loop. and inside that for loop, use convert string to StringBuilder.
3. Apply StringBuilder class built-in reverse feature.
For Example:
String s = "TestUser Loves Coding";
1. String words = s.split("\\s");
2. StringBuilder sb = new StringBuilder();
3. for(String s: words) {
sb = sb.append(new StringBuilder(w).reverse()).append(" ");
}
4. System.out.println(sb);
Output: resUtseT sevoL gnidoC
No comments:
Post a Comment