Answer the question
In order to leave comments, you need to log in
How to reverse a string while maintaining the position of individual characters?
Hello, it is necessary to reverse the string in the java language while maintaining the position of individual characters.
Here is an example of what needs to be done:
Input "m1mama soap ram5u"
Output "a1mam scarlet uma5r".
I manage to do the reverse in different ways, but I don’t know how to leave the numbers in their places.
I would be grateful for helpful advice.
Answer the question
In order to leave comments, you need to log in
Good afternoon!
You made a mistake, it should turn out a1amm scarlet wam5r .
Probably it is necessary to do a manual reverse of words with a condition.
Something like this (JAVA 1.8, PREDICATE - allows you to rearrange characters):
import java.util.StringJoiner;
import java.util.function.Function;
public class AppSwap {
public static final String WORD_DELIMITER = " ";
public static final Function<Character, Boolean> PREDICATE = character
-> character < '0' || character > '9';
public static void main(String[] args) throws Exception {
final String originalSequence = "м1ама мыла рам5у";
final String transformedSequence = transform(originalSequence);
System.out.println(originalSequence);
System.out.println(transformedSequence);
}
private static String transform(String originalSequence) {
// Split делим на слова
final String[] words = originalSequence.split(WORD_DELIMITER);
// Transform преобразуем
for (int i = 0; i < words.length; i++) {
words[i] = transformWord(words[i], PREDICATE);
}
// Join объединяем в предложение
final StringJoiner stringJoiner = new StringJoiner(WORD_DELIMITER);
for (int i = 0; i < words.length; i++) {
stringJoiner.add(words[i]);
}
return stringJoiner.toString();
}
private static String transformWord(final String inputWord, final Function<Character, Boolean> predicate) {
final char[] chars = inputWord.toCharArray();
for (int i = 0; i < chars.length / 2; i++) {
final int startIndex = i;
final int lastIndex = chars.length - 1 - i;
if (
predicate.apply(chars[startIndex])
&& predicate.apply(chars[lastIndex])
) {
// Swap \ Обмен символами
swapChars(chars, startIndex, lastIndex);
}
}
return new String(chars);
}
private static void swapChars(final char[] chars, final int startIndex, final int lastIndex) {
final char temp = chars[startIndex];
chars[startIndex] = chars[lastIndex];
chars[lastIndex] = temp;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question