user3442748 user3442748 - 3 months ago 31
Java Question

Reverse word letters in a sentence java

For my program I want to reverse letters in a line of text. However I don't want to reverse the order of the words in the sentence.
For example when I input: "This is a string"

I get: gnirts a si siht

But I want: siht si a gnirts

public static String reverseWordCharacters(String text1) {
String reverse = "";
int length = text1.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + text1.charAt(i);
System.out.println();
}
return reverse;
}

}

Answer
String sentence = "This is a string";
String[] words = sentence.split(" ");
String invertedSentece = "";
for (String word : words){
    String invertedWord = "";
    for (int i = word.length() - 1; i >= 0; i--)
        invertedWord += word.charAt(i);
    invertedSentece += invertedWord;
    invertedSentece += " ";
}
invertedSentece.trim();