java反转字符串

字符串的反转

public class StringTest {

public static void main(String[] args) {

                String  str = "abcdefg";

                //数组

char[] ary = new char[str.length()];
for(int i = 0;i < str.length();i++){
ary[i] = str.charAt(str.length() - i - 1);
}
System.out.println(String.valueOf(ary));

                //利用栈的特点

Stackstack = new Stack();
char[] chArray = str.toCharArray();
for(Character ch:chArray){
stack.add(ch);
}
for(int i = 0 ;i < str.length();i++){
chArray[i] = stack.pop();
}

System.out.println(String.valueOf(chArray));

                //逆遍历

                char[] cary = str.toCharArray();
for(int i = str.length()-1;i > -1; i--){
cary[str.length() - i-1] = str.charAt(i);
}
System.out.println(String.valueOf(cary));

                //利用Stringbuffer中的reverse方法

                System.out.println(new StringBuffer(str).reverse().toString());

}

}

数字的反转

public class numberTest{

    public static void main(String[] args){

          int num = 123456;
          int result = 0;
  while(true){
      int n = num % 10;
      result = result * 10 + n;
      num = num / 10;
      if(num == 0){
          break;
      }
         }
System.out.println(result);

    }

}

你可能感兴趣的:(数据结构)