Сделайте это следующим образом:
public class Main {
public static void main(String[] args) {
System.out.println(reverseWordsRetainingPositionCase("HeLlo woRld BEn"));
}
static String reverseWordsRetainingPositionCase(String str) {
String[] words = str.split("\\s+");// Split the string on space(s)
StringBuilder sb = new StringBuilder(str);// Create a StringBuilder instance with the content of str
for (String word : words) {
// Find the word in sb and replace it with its reverse
sb.replace(sb.indexOf(word), sb.indexOf(word) + word.length(), reverseCharsRetainingPositionCase(word));
}
return sb.toString();
}
static String reverseCharsRetainingPositionCase(String word) {
StringBuilder reversedWord = new StringBuilder(word).reverse();// Reverse the word
for (int i = 0; i < word.length(); i++) {
// If the character at i in the word is in upper case, change the case of the
// character at i in the reversed word to upper case. Process the reversed word
// in the same way for lower case.
if (Character.isUpperCase(word.charAt(i))) {
reversedWord.setCharAt(i, Character.toUpperCase(reversedWord.charAt(i)));
} else if (Character.isLowerCase(word.charAt(i))) {
reversedWord.setCharAt(i, Character.toLowerCase(reversedWord.charAt(i)));
}
}
return reversedWord.toString();
}
}
Вывод:
OlLeh dlRow NEb
Я добавил достаточно комментариев в код, чтобы его было легче понять. Не стесняйтесь комментировать в случае каких-либо сомнений / проблем.