- 9

How to reverse a string in java

This is a Java code project

7th Jun 2021, 2:24 AM
Titanus Gojira
Titanus Gojira - avatar
8 Answers
7th Jun 2021, 7:39 AM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 3
Narashima Murthy, In case you didn't know what tags in the forum is for https://code.sololearn.com/W3uiji9X28C1/?ref=app
7th Jun 2021, 2:53 AM
Ipang
+ 2
If you prefer not to use an array and keep it simple with just Strings, then: String myWord = "abc"; String reversed = ""; for (int i = myWord.length() - 1; i >= 0; i--) reversed += myWord.charAt(i); System.out.println(reversed);
8th Jun 2021, 6:13 PM
Yahel
Yahel - avatar
+ 2
public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] arr = text.toCharArray(); String reversed = ""; for(int i = arr.length - 1; i >= 0; i--) { reversed += arr[i]; } System.out.println(reversed); } } Use the for loop starting from the last item in the array and work backwards. Array items start at 0 so when using the length variable the last item in the array will be 1 less. e.g. An array length of 4 { 0 , 1 , 2 , 3 } Final item index is 3. Concatenate the character array items into a string using the operand +. The example above: reversed += arr[i]; Is the same as: reversed = reversed + arr[i]; Then print the string to console. You should store the result in a variable this can make it easy to call back to if you need to use it somewhere else. Hope this helps.
27th May 2022, 3:38 PM
Anthony Carnovale
0
lpang your web is beautiful
7th Jun 2021, 12:32 PM
Titanus Gojira
Titanus Gojira - avatar
0
Instead of using "println", in this case works better coding just "print". That way everything goes in the same line. So: 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(); //tu cĂłdigo va aquĂ­ for(int i=arr.length-1;i>=0;i--) { System.out.print(arr[i]); } } }
24th Oct 2021, 12:25 PM
CĂ©sar DĂ­az Amat
- 1
Thanking you buddy
7th Jun 2021, 12:30 PM
Titanus Gojira
Titanus Gojira - avatar
- 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(); for(int i=arr.length-1;i>=0;i--) { System.out.println(arr[i]); } } }
14th Jun 2021, 4:22 PM
Dharmi Sri
Dharmi Sri - avatar