reverse String - Java Algorithm

Java examples for Algorithm:String

Description

reverse String

Demo Code


public class Main {
  
  public static String reverseUsingArray(String str){
    if(str.length()<=1) return str;
    else{//www.  ja  v  a  2  s  .c om
      char temp;
      char[]  characters=str.toCharArray();
      for(int i=0; i<str.length()/2; i++){
        temp=characters[i];
        characters[i]=characters[str.length()-1-i];
        characters[str.length()-1-i]=temp;
      }
      return String.valueOf(characters);
    }
  }
  
  public static String reverseUsingString(String str){
    if(str.length()<=1) return str;
    else{
      String newStr="";
      for(int i=str.length()-1; i>=0; i--){
        newStr=newStr+str.charAt(i);
      }
      
      return newStr;
    }
  }
  public static void main(String[] args){
    String s_1 = "environmentalists";
    System.out.println(reverseUsingArray(s_1) );
  }
}

Related Tutorials