The main issue with your way of doing it is your taking the n'th character from str and appending it to make it the n'th character of res.
You could fix it like this:
public String reverseString(String str) {
String res = "";
for (int i = str.length() - 1; i >= 0; i--) {
res = res + str.charAt(i);
}
return res;
}
Answer from Jack Gore on Stack OverflowThe main issue with your way of doing it is your taking the n'th character from str and appending it to make it the n'th character of res.
You could fix it like this:
public String reverseString(String str) {
String res = "";
for (int i = str.length() - 1; i >= 0; i--) {
res = res + str.charAt(i);
}
return res;
}
You have your concatenation backwards. Try:
public String reverseString(String str) {
String res = "";
for (int i = 0; i < str.length(); i++) {
res = str.charAt(i) + res; // Add each char to the *front*
}
return res;
}
Note also the simpler, canonical, loop termination condition.
how to reverse a string in java
reversing a string with while loop
Videos
hey guys i need your help in java so i have a very beginner problem and i'll probably be laughed at for asking this but how do you reverse a string in java
so far the online called I've been given to work with is:
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
char[] arr = text.toCharArray();
//your code goes here
}
}
i don't know how to go about it, all i have to do is reverse the string. uhg it was so easy in python with just the (::-) is that how its written idk it's been some time python.
anyways i would appreciate any help and advice on learning java effectively i don't know much yet, i tried going on leetcode but daaaaamn it was crazy hard, i didn't manage to do any problem. thank you