package com.itheima;
import java.util.ArrayList;
import java.util.Iterator;
/*
*5、将字符串中进行反转。abcde --> edcba
* 思路:首先将字符串进行拆分成字符型数组,然后反向添加到存放到ArrayList集合中,最后进行遍历集合中的元素。
*/
public class Test5 {
public static void main(String[] args) {
//进行翻转输出的字符串
String str = "abcde";
System.out.println("字符串翻转之前:");
System.out.println(str);
System.out.println("字符串翻转之后:");
//进行翻转
resever(str);
}
private static void resever(String str){
//将字符串转换成字符数组
char[] ch = str.toCharArray();
//定义ArrayList集合
ArrayList<Character> al = new ArrayList<Character>();
//将字符串的元素逆序添加到ArrayList集合
for (int x = 0; x < ch.length; x++) {
al.add(ch[ch.length-1-x]);
}
//遍历ArrayList集合,并打印
Iterator<Character> it = al.iterator();
while(it.hasNext()){
System.out.print(it.next());
}
}
}
|
|