I need to reverse only letters in String and keep symbols and numbers in the same place using Character.isLetter and also I need to keep the same order of the reversed words.
My code reverses a string and keeps symbols and numbers in place but changes the order of the words, for example:
My input string:
a1bcd efg!h
My output string:
h1gfe dcb!a
Instead my output supposes to be:
d1cba hgf!e
class AnagramsMaker {
public static String createAnagram(String StringToReverse) {
char[] stringToChar = StringToReverse.toCharArray();
int arrayStart = 0;
int arrayEnd = stringToChar.length - 1;
while (arrayStart < arrayEnd) {
if (Character.isLetter(stringToChar[arrayStart]) && Character.isLetter(stringToChar[arrayEnd])) {
char temp = stringToChar[arrayStart];
stringToChar[arrayStart] = stringToChar[arrayEnd];
stringToChar[arrayEnd] = temp;
arrayStart++;
arrayEnd--;
}
else if (Character.isLetter(stringToChar[arrayStart]) && !Character.isLetter(stringToChar[arrayEnd])) {
arrayEnd--;
}
else if (!Character.isLetter(stringToChar[arrayStart]) && Character.isLetter(stringToChar[arrayEnd])) {
arrayStart++;
}
else {
arrayStart++;
arrayEnd--;
}
}
return String.valueOf(stringToChar);
}
}
With the way you currently you have it, you don't actually need to modify your method at all and can instead utilize it to reverse each word instead of the entire
Stringat once.I renamed your current method to
public static String createAnagramWord(String StringToReverse)and then created the method below:Where I use your current method with
createAnagramWord(s)inside of it.In this method note that I split the
Stringpassed to it on blank spaces with" "(you can also use\\s+instead, see this post), and then iterate on the array returned fromsplitusing an enhancedforloop.Inside of the
forloop the newStringis created by appending each reversed word along with a space.Example Run:
Output:
Note:
Appending
Stringin a loop should technically utilizeStringBuilder, however, I believed that is out of scope of this question and decided to omit it.Additionally, you can rework this logic into your current method if for some reason you prefer not to separate the logic into two separate methods.