How to print the reverse of the String java is object orientated language
without using any predefined function like reverse()
?
import java.util.Scanner;
public class StringReverse {
public static void main(String[] args) {
//Read user Data From Console
Scanner sc = new Scanner(System.in);
System.out.println("Enter Your String:");
//Take an String so that it can Store the string data
String s1 = sc.nextLine();
//split the string and keep in an array
String[] s2 = s1.split(" ");
String s3 = " ";
//reverse the string and placed in an String s3
for (int i = 0; i < s2.length; i++) {
for (int j= s2[i].length()-1;j>=0;j--) {
s3 += s2[i].charAt(j);
}//for
s3 += " ";
}//for
System.out.println("After Reverse: "+s3);
}//main
}//StringReverse
Here's a recursive solution that just prints the string in reverse order. It should be educational if you're trying to learn recursion. I've also made it "wrong" by actually having 2 print
statements; one of them should be commented out. Try to figure out which mentally, or just run experiments. Either way, learn from it.
static void printReverse(String s) {
if (!s.isEmpty()) {
System.out.print(s.substring(0, 1));
printReverse(s.substring(1));
System.out.print(s.substring(0, 1));
}
}
Bonus points if you answer these questions:
String x = "stack overflow";
String reversed = "";
for(int i = x.length()-1 ; i>=0; i--){
reversed = reversed+ x.charAt(i);
}
System.out.println("reversed string is : "+ reversed);
Well, printing itself would suggest a predefined function...
Presumably, though, you could obtain the characters and concatenate them manually in reverse (i.e. loop over it backwards). Of course, you could say concatenation is a predefined function... so maybe the char array itself. But again... why?
Is the source allowed to contain "egaugnal detatneiro tcejbo si avaj" ;-p
Also - note that string reversal is actually pretty complex if you consider unicode combining characters, surrogate pairs, etc. You should note the caveat that most string reversal mechanisms will only deal with the more common cases, but may struggle with i18n.
public class ReverseString {
public static void main(String[] args) {
reverseString("HELLO");
}
public static String reverseString(String s){
char []arr=s.toCharArray();
for(int i= (arr.length)-1;i>=0;i--){
System.out.print(arr[i]);
}
String str=String.copyValueOf(arr);
return str;
}
Try this:
public class Test {
public static void main(String[] args) {
String s = "welcome";
for( int i=0, j = (s.length())-1; i <= j; j-- ) {
char c=s.charAt(j);
System.out.print(c);
}
}
}