0

How to reverse a string without using predefiend function

13th Aug 2019, 10:51 AM
Nirmal Mali
Nirmal Mali - avatar
6 ответов
+ 1
Convert string to char array and then reversing this array for example
13th Aug 2019, 10:58 AM
Marina Vasilyova
Marina Vasilyova - 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(); //your code goes here String rev = ""; for (char i : arr) rev = i + rev; System.out.println(rev); } }
18th Mar 2021, 9:42 AM
Vijayanathan Menakan
Vijayanathan Menakan - avatar
+ 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.
6th Jun 2021, 3:40 AM
Lam Wei Li
Lam Wei Li - avatar
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);
13th Aug 2019, 11:10 AM
Dlite
Dlite - avatar
0
Another way to do it: String str = “Hello”; for (int i = str.length()-1; i >= 0; i—) System.out.print(str.charAt(i));
13th Aug 2019, 7:43 PM
Juan Debenedetti
Juan Debenedetti - avatar
0
Thanks to all who suggested me different different logics thanks alot...
12th Sep 2021, 5:25 AM
Nirmal Mali
Nirmal Mali - avatar