String reverse example

String reverse example


public class StringreverseExample {
    public static void main(String[] args) {
     
      String name="surendra";
      String nameinReverse="";
     
     
      //splitting  string into char[]
     
      char[] letters=name.toCharArray();
      //using length  finding last character in character array and appending
      //characters to nameinReverse(new string)
      for(int  length=letters.length-1;length>=0;length--){
      
       nameinReverse=nameinReverse+letters[length];
      }
     
    System.out.println("Enterd name :::>"+name+":::name after reverse:::"+nameinReverse);
    }
}

output:

Enterd name :::>surendra:::name after reverse:::ardnerus

String reverse example2 with out using toCharArray:


public class StringReverseExample2 {
    public static void main(String[] args) {
        String name="hemanth";
        String nameinReverse="";
        String[] strings = new String[name.length()] ;

 //using patterns we are generating sting[]
        String pattern = "[a-z]*";
       
        for(int i=0,j=1;i<name.length()|j<=name.length();i++,j++){
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(name);
            m.region(i, j);
            if (m.find( )) {
                String string = m.group();
                strings[i]=string;
            }
        }
     
     
        for(int i=strings.length-1;i>=0;i--){
           nameinReverse=nameinReverse+strings[i];
        }
           
        System.out.println("Enterd name :::>"+name+":::name after reverse:::"+nameinReverse);
     
    }
}


output:

Enterd name :::>hemanth:::name after reverse:::htnameh







Author

Written by Admin

Aliquam molestie ligula vitae nunc lobortis dictum varius tellus porttitor. Suspendisse vehicula diam a ligula malesuada a pellentesque turpis facilisis. Vestibulum a urna elit. Nulla bibendum dolor suscipit tortor euismod eu laoreet odio facilisis.

0 comments: