- class StringTest
- {
- public static void main(String[] args)
- {
- String s=" abcdefg ";
- sop("("+s+")");
- sop("("+reverseString(s)+")");
- System.out.println("Hello World!");
- }
- //将字符串反转
- /*
- 变成数组,对数组反转,变成字符串
- */
- public static String reverseString(String s)
- {
- char[] chs=s.toCharArray();
- reverse(chs);
- return new String(chs);
- }
- private static void reverse(char[] arr)
- {
- for(int start=0,end=arr.length-1;start<end;start++,end--)
- {
- swap(arr,start,end);
- }
- }
- private static void swap(char[] arr,int x,int y)
- {
- char temp=arr[x];
- arr[x]=arr[y];
- arr[y]=temp;
- }
- public static void sop(String obj)
- {
- System.out.println(obj);
- }
- }
复制代码
运行结果:
- E:\sourcefile>java StringTest
- ( abcdefg )
- ( gfedcba )
- Hello World!
复制代码 |
|