Как развернуть строку в java

от admin

Реверс строки в 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

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

Examples:

Following are some interesting facts about String and StringBuilder classes :

  1. Objects of String are immutable.
  2. String class in Java does not have reverse() method, however, the StringBuilder class has built-in reverse() method.
  3. StringBuilder class do not have toCharArray() method, while String class does have toCharArray() method.

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.

Implementation:

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

Method:

Implementation:

  • Convert the input string into character array by using the toCharArray(): Convert the input string into character array by using the toCharArray() – built in method of the String Class. Then, scan the character array from both sides i.e from the start index (left) as well as from last index(right) simultaneously.

Implementation:

  • Using ArrayList object: Convert the input string into the character array by using toCharArray() built in method. Then, add the characters of the array into the ArrayList object. Java also has built in reverse() method for the Collections class. Since Collections class reverse() method takes a list object, to reverse the list, we will pass the ArrayList object which is a type of list of characters.

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:

  • Reversing String by taking input from user-

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.

How to Reverse A String In Java?

A string is a sequence of characters that is considered to be an object in Java. In, there are various operations that you can perform on the String object. One of the most widely used operations on a string object is String Reverse. In this article, I will tell you the various approaches to Reverse a String in Java.

In Java, a String can be reversed in five different ways. They are as follows:

  1. Reverse a String using CharAt Method
  2. String reverse using String Buffer/String Builder Approach
  3. Reverse a String using Reverse Iterative Approach
  4. String reverse using Recursion
  5. Reverse the letters present in the String

Now let’s get into the details of each of these approaches starting off by understanding how to reverse a String in Java using CharAt method.

1. Reverse a String using CharAt Method

In the below given Java program will help you to understand how to reverse a String entered by the user. Here, I have used the CharAt() method in order to extract the characters from the input String. The main task of the CharAt() method is to return the character at the specified index in the given String. Then, I have appended them in reverse order to reverse the given String. It is one of the simple approaches to reverse a String in Java.

Читать:
Сколько страниц в тысячах будет найдено по запросу фрегат

When you execute this program, the output looks like as shown below:

I hope you understood how to reverse a given Java String with this simple approach. Now let’s move further and understand how to reverse a String using String Buffer/ StringBuilder Class.

2. Reverse a String using String Builder / String Buffer Class

StringBuffer and StringBuilder comprise of an inbuilt method reverse() which is used to reverse the characters in the StringBuffer. This method replaces the character sequence in the reverse order. Below is the code to reverse a String using a built-in method of the StringBuffer class.

On executing the above code, the output will be as shown below:

This is all about StringBuilder Class. Alternatively, you can also use a StringBuffer class reverse() method just like StringBuilder. Let’s take a look at the code below.

When you run the program, the output will the same as that of the StringBuilder class.

Note: You can either reverse as String using StringBuffer reverse() as shown in the above program or you can simply use the code logic as shown below:

Both StringBuilder and StringBuffer has the same approach of reversing a String in Java. But, StringBuilder is preferred as it is not synchronized and is faster than StringBuffer. Having understood this, let’s delve deeper into this article and learn one more approach to reverse a String in Java.

3. Reversing a String using Reverse Iteration

In this approach, I have first converted the given String to Character Array using CharArray() method. After that, I have just iterated the given array in the reverse order.

I hope you understood how to use the reverse iteration approach to reverse a String in Java. Now let’s move further and understand reversing a String using recursion.

4. String Reverse using Recursion

Recursion is nothing but a function that calls itself. In this approach, I will write a method that reverses the String by calling itself recursively. Let’s implement and check how it works.

In the above code, I created the object for the class StringRecursion r. Then, I have read the entered String using sc.nextLine() and stored it in the String variable s. Finally, I called the reverse method as . Having understood this, let’s now understand the last approach in this article. Here, I will tell you how to reverse the letters present in the given String.

5. Reverse the letters present in the String

This entered by the user. It doesn’t reverse the entire String as seen earlier in the previous approaches. For Example Java program reverses letters present in a S tringHello People will be termed as olleH elpoeP. Let’s implement the same using Java.

The output of the above program will be as shown below:

So, that was all about reversing the letters in the given String. This brings us to the end of the article on Reverse a String in Java. I hope you found it informative.

This brings us to the end of our blog on Advanced Java Tutorial. I hope you found this blog informative and added value to your knowledge.
If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Java.

Как перевернуть строку

В этой статье мы рассмотрим несколько способов, как перевернуть (инвертировать) строку.

Инвертируем строку с помощью StringBuilder

Самый простой способ, который не требует никаких дополнительных библиотек – это использовать стандартный StringBuilder:

Результат инвертирования строки:

Переворачиваем строку с помощью библиотеки StringUtils

Если в вашем проекте уже подключена библиотека StringUtils, будет удобно воспользоваться именно ею. Если вы не подключили библиотеку, это можно сделать с помощью подключения зависимости в файле pom.xml:

Теперь, для того, чтобы вывести строку в обратном порядке, воспользуемся методом StringUtils.reverse:

Кстати, в этом же классе есть метод StringUtils.reverseDelimited, который инвертирует строку не посимвольно, а по слова. Ему требуется указать на вход строку и разделитель между словами:

Инвертируем строку с помощью массива char[]

Приведённые выша два способа инвертирования строки являются наиболее простыми, читаемыми и удобными. Но на всякий случай приведём ещё один способ с помощью массива char:

Здесь мы сначала преобразуем входную строку в массив символов, затем последовательно меняем символы местами, используя промежуточную переменную temp. Результат выполнения такой программы:

Этот способ является более громоздким и менее удобным, поэтому рекомендуем вам использовать именно первые два способа. Тем не менее, этот вопрос может встречаться на собеседовании на позицию Junior Java Developer

Заключение

Существует множество способов инвертировать строку в Java. В данной статье мы показали наиболее удобные из них.

Похожие статьи