Reverse a String in Java

Reverse a string in Java

You can use this:

new StringBuilder(hi).reverse().toString()

StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.

Java reverse string method

The fixed code is

public class Test {
public static String reverse(String a) {
int j = a.length();
char[] newWord = new char[j];
for (int i = 0; i < a.length(); i++) {
newWord[--j] = a.charAt(i);
}
return new String(newWord);
}

public static void main(String a[]) {

String word = "abcdefgh";
System.out.println(reverse(word));
}
}

Like others have mentioned, arrays indexes start at 0. So if an array has size 5 for example it has indices 0,1,2,3,4. It does not have an index 5.

For an example of a string with length 5, the code change that I did newWord[--j] = a.charAt(i); will assign to the indices 4,3,2,1,0 in that order.

Regarding getting a good start in Java, I think you could try https://softwareengineering.stackexchange.com/. This site is not meant for that kind of thing.

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

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.

Reverse String characters in java

You simply need to loop through the array backwards:

for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}

You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).

This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).

how to reverse only numbers in a string

You can use the Java regex API and StringBuilder to solve it easily. The regex, \d+ specifies one or more digits. Using the Java regex API, you find the numbers, their start position and the end positions which you can use to build the required string.

Demo:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
public static void main(String[] args) {
// Tests
String[] samples = { "123ABC458", "123ABC458XYZ", "123ABC458XYZ367", "ABC123XYZ", "ABC123XYZ" };
for (String s : samples)
System.out.println(numbersInverted(s));

}

static String numbersInverted(String str) {
StringBuilder sb = new StringBuilder();
Matcher matcher = Pattern.compile("\\d+").matcher(str);
int lastInitialPos = 0;
while (matcher.find()) {
int start = matcher.start();
String inverted = new StringBuilder(matcher.group()).reverse().toString();
sb.append(str.substring(lastInitialPos, start)).append(inverted);
lastInitialPos = matcher.end();
}
if (sb.length() == 0) // If no number was found
return str;
else
return sb.append(str.substring(lastInitialPos)).toString();
}
}

Output:

321ABC854
321ABC854XYZ
321ABC854XYZ763
ABC321XYZ
ABC321XYZ

ONLINE DEMO

Reversing a String from user's input

Here's an explanation of what's happening.

public static void main(String[] args) {
String original = "", reverse = ""; // Create empty variables to hold the input and output
Scanner in = new Scanner(System.in); // Create an object to read from StdIn

while(!original.contains("exit"))
// Read from StdIn as long as user does not input "exit"
{
original = "";
reverse = "";
System.out.println("Enter a sentence to be reversed: ");
original = in.nextLine(); // Save the user's input as "original"

int length = original.length(); // Get the length of the input
for (int i = length - 1; i >= 0; i--) // Iterate over each character of the input, starting from the end until you reach the beginning and add the character to the "reverse" string
reverse = reverse + original.charAt(i);

System.out.println(reverse); // Output the result
}
}

Having two separate comments to explain the for loop doesn't make much sense as each of the two lines are meaningless without the other.



Related Topics



Leave a reply



Submit