+ 3

Reverse string in java

String s="hello"; int length=s.length(); String s1=""; for(int j=1;j<=length; j++) { s1+=s[length-j]; // shows me error here ..array required but string found System.out.println(s1); } how to rectify it?? help me plz

18th Sep 2017, 4:01 PM
corejava
9 Answers
+ 13
String s="hello"; int n=0,length=s.length(); String f,r=""; while(n<length) { f=s.Substring(n,n+1); r=f.concat(r); n++; } System.out.print(r); //see this â˜ș
18th Sep 2017, 4:12 PM
Changed
Changed - avatar
+ 12
dude ... s is not string array ... thats the mistake
18th Sep 2017, 4:05 PM
Changed
Changed - avatar
+ 11
@sahil replace "Substring" by "substring" , by mistake i written the method name initial as capital & java is case sensitive //it is working now â˜ș👍
19th Sep 2017, 4:28 AM
Changed
Changed - avatar
+ 6
More effecient than subString: String myString = "theString"; char[] array = myString.toCharArray(); for(int i = 0; i < array.length / 2; i++){ char temp = array[i]; array[i] = array[array.length - i - 1]; array[array.length - i - 1] = temp; } myString = String.valueOf(array);
19th Sep 2017, 5:10 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
String s = "string"; StringBuilder sb = new StringBuilder(s); System.out.println(sb.reverse());
19th Sep 2017, 5:03 PM
John Johni
+ 3
@Gaurav Agrawal hii bro.... this code is giving error in line s.Substring(n,n+1)... rectify your own self.....
19th Sep 2017, 3:01 AM
Sahil Luthra
Sahil Luthra - avatar
+ 3
@Gaurav ...ohh thnks buddy
19th Sep 2017, 7:02 AM
Sahil Luthra
Sahil Luthra - avatar
+ 2
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]); }// Just we start printing from back side } }
14th Jun 2021, 4:25 PM
Dharmi Sri
Dharmi Sri - avatar
+ 1
but if I give in string array [0] I'll put hello into them not h
18th Sep 2017, 4:06 PM
corejava