How to reverse string in java

How to reverse string in java

Reverse a string in Java

This article discusses different ways to reverse a string in Java with examples.

Examples:

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Following are some interesting facts about String and StringBuilder classes :

Implementation:

Converting String into Bytes: getBytes() method is used to convert the input string into bytes[].

Method:

Implementation:

Using built in reverse() method of the StringBuilder class:

String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder. After that, print out the characters of the reversed string by scanning from the first till the last index.

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Implementation:

Converting String to character array: The user input the string to be reversed.

Method:

Implementation:

Implementation:

Implementation:

Using StringBuffer:

String class does not have reverse() method, we need to convert the input string to StringBuffer, which is achieved by using the reverse method of StringBuffer.

Implementation:

In the above code, we are essentially reading a String from the user before starting an iteration loop to create a new, inverted String. The “charAt” function of the String class is used to retrieve each character of the original String individually from the end, and the “+” operator is used to concatenate them into a new String.

Reverse string в Java: учимся реверсировать строки разными способами

1. StringBuilder/StringBuffer

2. Решение с массивом

3. Решение с charAt

4. Решение со Stack

5. Решение рекурсией

способ первый

Переменные rightStr и leftStr мы используем для разбивки пришедшей строки на две равные части. Далее с помощью такой разбивки мы дробим строку на наименьшие делимые части (1 символ). После рекурсия начинает сворачиваться, возвращая символы в противоположном порядке (те, что были справа — поставили слева; те, что были слева — вправо)

Нельзя забывать, что каждая рекурсия — это многократный вызов метода, и как следствие — немалые затраты ресурсов. Ну а если мы говорим о рекурсии с недостижимым условием выхода, то это путь в бесконечность и к StackOverflowError.

способ второй

Здесь нам понадобится дополнительный аргумент в методе — index.

Индекс у нас служит индикатором того, какой элемент строки мы будем использовать сейчас (а элементы мы будем использовать с конца).

Поэтому задаём условия выхода при достижении индексом первого элемента.

Складываем значения полученного с помощью индекса letter с результатом предыдущего выполнения метода и возвращаем результат.

Данный способ по сути является самым простым из рекурсивных. А как мы помним, простое = лучшее.

Во время каждого запуска мы задаем ту же строку, но без первого элемента. При достижении условия выхода (когда у нас останется один символ) рекурсия начинает сворачиваться, и к каждому последующему результату будет добавляться предыдущий неиспользованный символ.

6. При помощи XOR

arr[low] = (char) (arr[low] ^ arr[high]);

arr[high] = (char) (arr[low] ^ arr[high]);

arr[low] = (char) (arr[low] ^ arr[high]);

В итоге благодаря этим операциям мы поменяли местами значения двух ячеек массива. How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in javaarr[high] отдален от конца массива на столько же элементов, на сколько arr[low] отдален от начала. Поэтому мы просто меняем элементы с этими индексами местами. Например, при первом выполнении в предложении «JavaRush forever»J и r поменяются местами, при втором — a и e и т. д. Если у нас нечетное количество символов, то при достижении элемента, который находится посередине, нас выбросит из цикла (т.к. средний элемент менять и не нужно). Если чётное — нас выбросит после обработки всех элементов. Ну а после мы заходим в обычный цикл и строим строку из элементов массива.

What is the most efficient algorithm for reversing a String in Java?

What is the most efficient way to reverse a string in Java? Should I use some sort of xor operator? The easy way would be to put all the chars in a stack and put them back into a string again but I doubt that’s a very efficient way to do it.

And please do not tell me to use some built in function in Java. I am interested in learning how to do it not to use an efficient function but not knowing why it’s efficient or how it’s built up.

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

22 Answers 22

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You say you want to know the most efficient way and you don’t want to know some standard built-in way of doing this. Then I say to you: RTSL (read the source, luke):

Check out the source code for AbstractStringBuilder#reverse, which gets called by StringBuilder#reverse. I bet it does some stuff that you would not have considered for a robust reverse operation.

The following does not deal with UTF-16 surrogate pairs.

You said you don’t want to do it the easy way, but for those Googling you should use StringBuilder.reverse:

If you need to implement it yourself, then iterate over the characters in reverse order and append them to a StringBuilder. You have to be careful if there are (or can be) surrogate pairs, as these should not be reversed. The method shown above does this for you automatically, which is why you should use it if possible.

An old post & question, however still did not see answers pertaining to recursion. Recursive method reverse the given string s, without relaying on inbuilt jdk functions

The fastest way would be to use the reverse() method on the StringBuilder or StringBuffer classes 🙂

If you want to implement it yourself, you can get the character array, allocate a second character array and move the chars, in pseudo code this would be like:

You could also run half the array length and swap the chars, the checks involved slow things down probably.

I’m not really sure by what you mean when you say you need an efficient algorithm.

The ways of reversing a string that I can think of are (they are all already mentioned in other answers):

Use a stack (your idea).

Create a new reversed String by adding characters one by one in reverse order from the original String to a blank String/StringBuilder/char[].

Exchange all characters in the first half of the String with its corresponding position in the last half (i.e. the ith character gets swapped with the (length-i-1)th character).

The thing is that all of them have the same runtime complexity: O(N). Thus it cannot really be argued that any one is any significantly better than the others for very large values of N (i.e. very large strings).

The third method does have one thing going for it, the other two require O(N) extra space (for the stack or the new String), while it can perform swaps in place. But Strings are immutable in Java so you need to perform swaps on a newly created StringBuilder/char[] anyway and thus end up needing O(N) extra space.

How to Reverse A String in Java Using Different Methods?

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Table of Contents

A string is a sequence of characters that behave like an object in Java. The string is one of the most common and used data structures after arrays. It is an object that stores the data in a character array.

For better clarity, just consider a string as a character array wherein you can solve many string-based problems.

Full Stack Java Developer Course

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Reverse in Java

Example: HELLO string reverse and give the output as OLLEH

How to Reverse a String in Java?

Since the strings are immutable objects, you need to create another string to reverse them. The string class doesn’t have a reverse method to reverse the string. It has a toCharArray() method to do the reverse.

By Using toCharArray()

The code below will help you understand how to reverse a string. By using toCharArray() method is one approach to reverse a string in Java.

The code also uses the length, which gives the total length of the string variable.

The for loop iterates till the end of the string index zero.

CodeВ

//ReverseString using CharcterArray.

public static void main(String[] arg) <

String stringinput = «Independent»;

В В В В В В В В // convert String to character array

В В В В В В В В // by using toCharArray

В В В В В В В В char[] resultarray = stringinput.toCharArray();

В В В В В В В В //iteration

В В В В В В В В // print reversed String

В В В В В В В В В В В В System.out.print(resultarray[i]);

Output

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

FREE Java Certification Training

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

By Using StringBuilder

Let us see how to reverse a string using the StringBuilder class. StringBuilder or StringBuffer class has an in-build method reverse() to reverse the characters in the string. This method replaces the sequence of the characters in reverse order. The reverse method is the static method that has the logic to reverse a string in Java.

In the code mentioned below, the object for the StringBuilder class is used.В

The StringBuilder objects are mutable, memory efficient, and quick in execution. But it also considers these objects as not thread-safe.

The object calls the in-built reverse() method to get your desired output.

This is a preferred method and commonly used to reverse a string in Java.

//ReverseString using StringBuilder.

public static void main(String[] arg) <

В В В В В В В В String input = «Independent»;

В В В В В В В В // creating StringBuilder object

В В В В StringBuilder stringBuildervarible = new StringBuilder();

В В В В // append a string into StringBuilder stringBuildervarible

В В В В //append is inbuilt method to append the data

В В В В stringBuildervarible.append(input);

В В В В // reverse is inbuilt method in StringBuilder to use reverse the stringВ

В В В В stringBuildervarible.reverse();

В В В В // print reversed String

В В В В System.out.println( «Reversed StringВ : » +stringBuildervarible);

Output:

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Alternatively, you can also use the StringBuffer class reverse() method similar to the StringBuilder. Both the StringBuilder class and StringBuffer class, work in the same way to reverse a string in Java. Considering reverse, both have the same kind of approach. Although, StringBuilder class is majorly appreciated and preferred when compared to StringBuffer class. The StringBuilder class is faster and not synchronized. These StringBuilder and StringBuffer classes create a mutable sequence of characters. To achieve the desired output, the reverse() method will help you.В

In Java, it will create new string objects when you handle string manipulation since the String class is immutable. The StringBuilder and StringBuffer classes are two utility classes in java that handle resource sharing of string manipulations.В

By Using While Loop or For Loop

Simply handle the string within the while loop or the for loop. Get the length of the string with the help of a cursor move or iterate through the index of the string and terminate the loop.

The loop prints the character of the string where the index (i-1).

The loop starts and iterates the length of the string and reaches index 0.

Code Using While Loop

// Java program to reverse a string using While loop

public class strReverse <

В В В В public static void main(String[] args)

В В В В String stringInput = «My String Output»;В В

В В В В //Get the String length

В В В В int iStrLength=stringInput.length();В В В В

В В В В //Using While loop

Output:

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Post Graduate Program: Full Stack Web Development

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Code Using For Loop

// Java program to reverse a string using For loop

public class strReverse <

В В В В public static void main(String[] args)

В В В В String stringInput = «My New String»;В В

В В В В //Get the String length

В В В В int iStrLength=stringInput.length();В В В В

В В В В //Using For loop

for(iStrLength=stringInput.length();iStrLength >0;— iStrLength)

Output:

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

By Converting a String to Bytes

The getBytes() method will split or convert the given string into bytes. The temporary byte array length will be equal to the length of the given string. Get the bytes in reverse order and store them in another byte array.

In the code below, a byte array is temporarily created to handle the string. The getBytes() is also an in-built method to convert the string into bytes. There are two byte arrays created, one to store the converted bytes and the other to store the result in the reverse order.

В Code

//ReverseString using ByteArray.

public static void main(String[] arg) <

String inputvalue = «Independent»;

В В В В // getBytes() is inbuilt methodВ to convert string

В В В В // into bytes[].

В В В В byte[] strAsByteArray = inputvalue.getBytes();

В В В В byte[] resultoutput = new byte[strAsByteArray.length];

В В В В // Store result in reverse order into the

В В В В // result byte[]

В В В В for (int i = 0; i How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

New Course: Full Stack Development for Beginners

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

By Using ArrayList Object

Using the built-in method toCharArray(), convert the input string into a character array. Then, in the ArrayList object, add the array’s characters. The Collections class in Java also has a built-in reverse() function. Since the reverse() method of the Collections class takes a list object, use the ArrayList object, which is a list of characters, to reverse the list.

Copy the String contents to an ArrayList object in the code below. Then, using the listIterator() method on the ArrayList object, construct a ListIterator object. To iterate over the array, use the ListIterator object. It also helps iterate through the reversed list and printing each object to the output screen one-by-one.

// Java program to Reverse a String using ListIterator

// Class of ReverseString

В В В В public static void main(String[] args)

В В В В В В В В String input = «Reverse a String»;

В В В В В В В В char[] str = input.toCharArray();

В В В В В В В В List revString = new ArrayList<>();

В В В В В В В В for (char c : str)

В В В В В В В В В В В В revString.add(c);

В В В В В В В В Collections.reverse(revString);

В В В В В В В В ListIterator li = revString.listIterator();

В В В В В В В В while (li.hasNext())

В В В В В В В В В В В В System.out.print(li.next());

Output:В

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

By Using StringBuffer

The String class requires a reverse() function, hence first convert the input string to a StringBuffer, using the StringBuffer method. Then use the reverse() method to reverse the string.

// Java program to convert String to StringBuffer and reverse of string

public class strReverse <

В В В В public static void main(String[] args)

В В В В В В В В String str = «String»;

В В В В В В В В // conversion from String object to StringBuffer

В В В В В В В В StringBuffer sbfr = new StringBuffer(str);

В В В В В В В В // To reverse the string

В В В В В В В В sbfr.reverse();

В В В В В В В В System.out.println(sbfr);

Output:В

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Full Stack Web Developer Course

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Using Stack

You can use the Stack data structure to reverse a Java string using these steps:

В В В В // Method to reverse a string in Java using a stack and character array

В В В В public static String reverse(String str)

В В В В В В В В // base case: if the string is null or empty

В В В В В В В В if (str == null || str.equals(«»)) <

В В В В В В В В В В В В return str;

В В В В В В В В >

В В В В В В В В // create an empty stack of characters

В В В В В В В В Stack stack = new Stack ();В

В В В В В В В В // push every character of the given string into the stack

В В В В В В В В char[] ch = str.toCharArray();

В В В В В В В В for (int i = 0; i How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Using Character Array

String is immutable in Java, which is why we can’t make any changes in the string object. However, we can use a character array:

В В В В // Method to reverse a string in Java using a character array

В В В В public static String reverse(String str)

В В В В В В В В // return if the string is null or empty

В В В В В В В В if (str == null || str.equals(«»)) <

В В В В В В В В В В В В return str;

В В В В В В В В >

В В В В В В В В // get string length

В В В В В В В В int n = str.length();

В В В В В В В В // create a character array of the same size as that of string

В В В В В В В В char[] temp = new char[n];

В В В В В В В В // fill character array backward with characters in the string

В В В В В В В В for (int i = 0; i How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Free Course: JavaScript for Beginners

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Using Recursion

Here, learn how to reverse a Java string by using the stack data structure. We can effortlessly convert the code, since the stack is involved, by using the recursion call stack. Because string is immutable, we must first convert the string into a character array. Once we’ve done this, we reverse the character array and wrap things up by converting the character array into a string again.

В В В В static int i = 0;

В В В В // Recursive method to reverse a string in Java using a static variable

В В В В private static void reverse(char[] str, int k)

В В В В В В В В // if the end of the string is reached

В В В В В В В В if (k == str.length) <

В В В В В В В В В В В В return;

В В В В В В В В >В

В В В В В В В В // recur for the next character

В В В В В В В В reverse(str, k + 1);В

В В В В В В В В if (i How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Using Substring() Method

Programmers can use the String.substring(int, int) method to recursively reverse a Java string. Here is one approach:

В В В В // Method to reverse a string in Java using recursion

В В В В private static String reverse(String str)

В В В В В В В В // base case: if the string is null or empty

В В В В В В В В if (str == null || str.equals(«»)) <

В В В В В В В В В В В В return str;

В В В В В В В В >

В В В В В В В В // last character + recur for the remaining string

В В В В public static void main(String[] args)

В В В В В В В В String str = «Techie Delight»;

В В В В В В В В // string is immutable

В В В В В В В В str = reverse(str);

В В В В В В В В System.out.println(«The reverse of the given string is: » + str);

Free Course: Java Hibernate Fundamentals

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Using the Character Array and swap() Method

Here’s an efficient way to use character arrays to reverse a Java string.

В В В В // Method to reverse a string in Java using a character array

В В В В public static String reverse(String str)

В В В В В В В В // return if the string is null or empty

В В В В В В В В if (str == null || str.equals(«»)) <

В В В В В В В В В В В В return str;

В В В В В В В В >

В В В В В В В В // create a character array and initialize it with the given string

В В В В В В В В char[] c = str.toCharArray();В

Using the Java Collections Framework reverse() Method

You can use Collections.reverse() to reverse a Java string. Use these steps:

В В В В // Method to reverse a string in Java using `Collections.reverse()`

В В В В public static String reverse(String str)

В В В В В В В В // base case: if the string is null or empty

В В В В В В В В if (str == null || str.equals(«»)) <

В В В В В В В В В В В В return str;

В В В В В В В В >

В В В В В В В В // create an empty list of characters

В В В В В В В В List list = new ArrayList ();В

В В В В В В В В // push every character of the given string into it

В В В В В В В В for (char c: str.toCharArray()) <

В В В В В В В В В В В В list.add(c);

В В В В В В В В >

В В В В В В В В В // reverse list using `java.util.Collections` `reverse()`

В В В В В В В В Collections.reverse(list);

В В В В В В В В // convert `ArrayList` into string using `StringBuilder` and return it

В В В В В В В В StringBuilder builder = new StringBuilder(list.size());

В В В В В В В В for (Character c: list) <

В В В В В В В В В В В В builder.append(c);

В В В В В В В В >В

В В В В В В В В return builder.toString();

В В В В В public static void main(String[] args)

В В В В В В В В String str = «Techie Delight»;

В В В В В В В В В // String is immutable

В В В В В В В В str = reverse(str);

В В В В В В В В System.out.println(«The reverse of the given string is: » + str);

Output

How to reverse string in java. Смотреть фото How to reverse string in java. Смотреть картинку How to reverse string in java. Картинка про How to reverse string in java. Фото How to reverse string in java

Conclusion

String objects in Java are immutable, which means they are unchangeable. Java works with string in the concept of string literal. When one reference variable changes the value of its String object, it will affect all the reference variables.

The string class is more commonly used in Java In the Java.lang.String class, there are many methods available to handle the string functions such as trimming, comparing, converting, etc. These methods also help you reverse a string in java.

You have now seen a vast collection of different ways to reverse a string in java. There are also a few popular third-party tools or libraries such as Apache Commons available to reverse a string in java.

If you are looking to master Java and perhaps get the skills you need to become a Full Stack Java Developer, Simplilearn’s Full Stack Java Developer Master’s Program is the perfect starting point. This six-month bootcamp certification program covers over 30 of today’s top Java and Full Stack skills. The curriculum sessions are delivered by top practitioners in the industry and, along with the multiple projects and interactive labs, make this a perfect program to give you the work-ready skills needed to land today’s top software development job roles.

If you have any feedback or suggestions for this article, feel free to share your thoughts using the comments section at the bottom of this page. Our experts will review your comments and share responses to them as soon as possible.В

About the Author

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

How to Reverse a String in Java

Reverse a string in Java is a quite easy task.

I’ll provide you 6 pieces of Java code to reverse a string.

I think StringBuilder.reverse() and StringBuffer.reverse() are the best string reverse functions in Java.

It’s already optimized, looks simple and easy.

But sometimes you have a task to implement string reversal using for loop, recursion or even reverse a string word by word.

Java Reverse String Methods Overview

So you have a task: you need to write a Java program to reverse a string.

To be more precise – you need to write a code to reverse letters in a string.

First of all, the difference is StringBuffer is threadsafe and StringBuilder is not.

If you take one of these reverse methods it would be a good choice.

It’s a source code of String Builder reverse method:

Looks a little bit complicated, but you shouldn’t care about it, it’s a problem of JDK developers.

The most important for you is that this method is well-optimized and tested.

I prepared code examples in the next sections. Let’s take a look.

String Builder Reverse

Easy, fast and well-tested way to reverse a string, but not threadsafe.

String Buffer Reverse

Easy, well-tested, threadsafe, but slower than StringBuilder.reverse().

String Utils Reverse

Apache Commons StringUtils is the most popular library to process strings.

It provides fancier API but uses StringBuilder.reverse() method inside.

To include this library you should add maven dependency to your pom.xml:

and use StringUtils reverse method.

Looks better but in general the same as a StringBuilder.

Reverse a String in a For Loop

The solution is simple:

Or you can switch reversed array of chars to StringBuilder.

Or even without retrieving char array.

Reverse a String Using Recursion

The reverse function looks easy:

For example, you want to reverse “Hello” string.

The method will be executed 6 times:

Reverse Word Letters in a String

The task is to keep words in its places but reverse characters in each word.

The plan is the following:

The example is in Java 8:

Reverse Words in String

The task is to reverse words in a string but letters in each word should not be changed.

The source code is in Java 8, but if someone needs I can provide an example without streams.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *