Saturday, August 19, 2017

String reverse without using functions in Java example?

Java API has a method a default methods to revert a string in StringBuilder class. But in interviews they will ask us to write a program without using function.

Here is the example:

public class strRev {

        public String sample;
        String rev ="";
 
        public String revStr(String s){
  
                if(s.length()<=1)
                     return s;
                rev+=s.charAt(s.length()-1)+revStr(s.substring(0,s.length()-1));
                return rev;
        }
 
        public static void main(String[] args) {
  
            strRev strrev=new strRev();
            String after = strrev.revStr("1234");
            System.out.println(after);
       }
}

No comments: