- 9
How to reverse a string in java
This is a Java code project
8 Respuestas
+ 4
1. use array
2. StringBuilder
https://code.sololearn.com/cy26M72V2D2g/?ref=app
https://code.sololearn.com/cpAv2CZejx67/?ref=app
+ 3
Narashima Murthy,
In case you didn't know what tags in the forum is for
https://code.sololearn.com/W3uiji9X28C1/?ref=app
+ 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);
+ 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.
0
lpang your web is beautiful
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]); }
}
}
- 1
Thanking you buddy
- 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]);
}
}
}