+ 1

Hi guys i have a question with a reverse string

In the code there was already char[] try1=text.tochararray(); Then i put int sum=0; char[] try1 = 10 ; //because i considered that hello there has 10 letters // then i used the loop for with try1.length to invert the letters for (int i= try1.length - 1; 1>=0; i--){ sum += try1[i] ; System.out.println (sum); This is how i did it, i can't get where i'm wrong and how i can do it well

30th Nov 2020, 10:20 PM
Michele Marchili
Michele Marchili - avatar
6 Respostas
+ 4
You just replace the string variable with the input. A String is a String the methods don't care if it is an input String or a String literal. In fact all of these examples had Scanner inputs initially, but I removed them and put String literals for simplicity, so you wouldn't need to provide your own input when you ran them. Edit: I've added to the StringBuilder example to work with an input as well. Same with the custom methods.
1st Dec 2020, 12:30 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Here's 3 examples of reversing a String. 1. Convert to char array and swap chars from front to end and end to front. O(log n) 2. Use Stringbuilder reverse method (preferred) 3. Convert to char array and add each char to the beginning of a new String. (Not recommended, not efficient) https://code.sololearn.com/cvXz4vpamhbM/?ref=app https://code.sololearn.com/cNKmT0m5L9KI/?ref=app https://code.sololearn.com/cpAQq32DskpS/?ref=app
30th Nov 2020, 11:24 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
int sum ; is an Integer variable so you can't add string to it. sum+=try1[i] will add charecter equalent ascii value to sum. So finally you get a Integer.. Use a charecter array or string.. And add. String st=""; st+= try[i]; will work.. Loop condition 1>=0, is it I or 1 , I>=0 is correct.
1st Dec 2020, 12:02 PM
Jayakrishna 🇮🇳
+ 1
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 String rev = ""; for (char i : arr) rev = i + rev; System.out.println(rev); } }
18th Mar 2021, 9:41 AM
Vijayanathan Menakan
Vijayanathan Menakan - avatar
0
I can't use them because the excercise use an imput and not a string already defined
30th Nov 2020, 11:53 PM
Michele Marchili
Michele Marchili - avatar
0
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 for (int i=arr.length -1; i >=0; i--) { System.out.print(arr[i]); } } }
19th Jun 2021, 5:42 AM
Aashiq Husaain
Aashiq Husaain - avatar