0
How to reverse a string without using predefiend function
6 ответов
+ 1
Convert string to char array and then reversing this array for example
+ 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);
}
}
+ 1
Using for-each for simplicity.
4 lines of code added.
https://code.sololearn.com/cig6PA96rplT/?ref=app
Your original code has splitted the String into an Char[] array.
For-each loop loops through the Char[] array, one Char (i) at a time, from left-to-right order.
String rev is the temporary result.
"rev = i + rev" means you are adding the i to the front, reversing the String.
0
String s = "Okay",sReverse ="";
//System.out.println(s);
for(int i=s.length();i>0;i--){
sReverse += s.substring(i-1,i);
}
System.out.println(sReverse);
0
Another way to do it:
String str = “Hello”;
for (int i = str.length()-1; i >= 0; i—)
System.out.print(str.charAt(i));
0
Thanks to all who suggested me different different logics thanks alot...