How to Reverse a String in Java
We’ll start to do this processing using plain Java solutions. Next, we’ll have a look at the options that the third-party libraries like Apache Commons provide.
Furthermore, we’ll demonstrate how to reverse the order of words in a sentence.
2. A Traditional for Loop
We know that strings are immutable in Java. An immutable object is an object whose internal state remains constant after it has been entirely created.
Therefore, we cannot reverse a String by modifying it. We need to create another String for this reason.
First, let’s see a basic example using a for loop. We’re going to iterate over the String input from the last to the first element and concatenate every character into a new String:
As we can see, we need to be careful at the corner cases and treat them separately.
In order to better understand the example, we can build a unit test:
3. A StringBuilder
Java also offers some mechanisms like StringBuilder and StringBuffer that create a mutable sequence of characters. These objects have a reverse() method that helps us achieve the desired result.
Here, we need to create a StringBuilder from the String input and then call the reverse() method:
4. Apache Commons
Apache Commons is a popular Java library with a lot of utility classes including string manipulation.
As usual, to get started using Apache Commons, we first need to add the Maven dependency:
The StringUtils class is what we need here because it provides the reverse() method similar to StringBuilder.
One advantage of using this library is that its utility methods perform null-safe operations. So, we don’t have to treat the edge cases separately.
Let’s create a method that fulfills our purpose and uses the StringUtils class:
Now, looking at these three methods, we can certainly say that the third one is the simplest and the least error-prone way to reverse a String.
5. Reversing the Order of Words in a Sentence
Now, let’s assume we have a sentence with words separated by spaces and no punctuation marks. We need to reverse the order of words in this sentence.
We can solve this problem in two steps: splitting the sentence by the space delimiter and then concatenating the words in reverse order.
First, we’ll show a classic approach. We’re going to use the String.split() method in order to fulfill the first part of our problem. Next, we’ll iterate backward through the resulting array and concatenate the words using a StringBuilder. Of course, we also need to add a space between these words:
Second, we’ll consider using the Apache Commons library. Once again, it helps us achieve a more readable and less error-prone code. We only need to call the StringUtils.reverseDelimited() method with the input sentence and the delimiter as arguments:
6. Conclusion
In this tutorial, we’ve first looked at different ways of reversing a String in Java. We went through some examples using core Java, as well as using a popular third-party library like Apache Commons.
Next, we’ve seen how to reverse the order of words in a sentence in two steps. These steps can also be helpful in achieving other permutations of a sentence.
As usual, all the code samples shown in this tutorial are available over on GitHub.
Реверс строки в Java
Строка – это последовательность символов, которая считается объектом в Java. Существуют различные операции, которые вы можете выполнять над объектом String. Одной из наиболее часто используемых операций над строковым объектом является реверс.
1. Использование метода CharAt
В приведенной ниже программе вы сможете понять, как перевернуть строку в Java, введенную пользователем. Здесь использован метод CharAt() для извлечения символов из входной строки. Основная задача метода – вернуть символ по указанному индексу в указанной строке. Затем добавили их в обратном порядке, чтобы изменить заданную строку. Это один из простых вариантов.
Когда вы выполняете эту программу, вывод выглядит так, как показано ниже:
2. Использование классов String Builder/String Buffer
StringBuffer и StringBuilder содержат встроенный метод reverse(), который используется для обращения символов. Этот метод заменяет последовательность символов в обратном порядке.
При выполнении приведенного выше кода результат будет таким, как показано ниже:
Кроме того, вы также можете использовать метод reverse() класса StringBuffer, как и StringBuilder. Давайте посмотрим на код ниже.
При запуске программы выходные данные будут такими же, как и у класса StringBuilder.
Примечание: можете обратить как String, используя StringBuffer reverse(), как показано в приведенной выше программе, либо просто использовать логику кода, как показано ниже:
И StringBuilder, и StringBuffer имеют одинаковый подход к реверсу строки в Java. Но StringBuilder предпочтительнее, поскольку он не синхронизирован и работает быстрее, чем StringBuffer.
3. Использование обратной итерации
Сначала преобразовываем данную строку в символьный массив, используя метод CharArray(). После этого просто перебираем данный массив в обратном порядке.
4. Использование рекурсии
Рекурсия – это не что иное, как функция, которая вызывает сама себя.
В приведенном выше коде создан объект для класса StringRecursion r. Затем прочитана введенная строка с помощью sc.nextLine() и сохранена в строковую переменную s. Наконец, вызван обратный метод, как r.rev (s).
5. Меняем местами буквы в строке
Эта программа реверсирует буквы, присутствующие в строке, введенной пользователем. Не переворачивает всю строку, как было показано ранее в предыдущих примерах. Например: Hello People будет называться olleH elpoeP.
О разворачивании строк в Java
Прочитав хабротопик О разворачивании строк в .Net/C# и не только, меня заинтересовало а как обстоят дела с той же проблемой в Java.
Не имея под руками машины с медленной памятью пришлось ограничится тестами на одной.
Времени проводить такое количество тестов как автор произвел в оригинале нету поэтому ограничусь проверкой нескольких мыслей однако тенденция в Java соблюдается — StringBuilder самый медленный результат.
Параметры машины: Intel® Core(TM) 2 Duo CPU E4600 @2.40GHz; 4GB Ram DDR2 (частоту к сожалению не скажу)
Своп напрочь отключён ОС — WinXP SP2.