Reverse a string (in 3 ways)
package ProgramsPractice;
import java.io.StringBufferInputStream;
import java.nio.charset.Charset;
public class ReverseString {
public static void main(String[] args) {
// 1.string concatenation
String s="amazon";
int length=s.length();
System.out.println(length);
String rev="";
for(int i=length-1;i>-1;i--) {
rev= rev+ s.charAt(i);
}
System.out.println("Reversed String is "+ rev);
//2. using characterarray
String p="amazon";
int length=p.length();
char[] arr=p.toCharArray();
String rev="";
for(int i=length-1; i>=0;i--) {
rev=rev+arr[i];
}
System.out.println(rev);
//3. using string bufferclass
String str="Shiva";
StringBuffer sb= new StringBuffer(str);
System.out.println(sb.reverse());
}
}
Comments
Post a Comment