当前位置 博文首页 > ALiuchj的博客:使用 java 拆分字符串和拼接字符串
1.拆分字符串
String []?tempName ;
List<String>mlistName? = new ArrayList<>();
mNames = "dasjdask,dasjdsahdsa,dsdsahadsh,dsah,dasasdasd,adssadadsfw”
?tempName = mNames.split(",");
? //把集合转化为数组
?mlistName =Util.toArrayList(tempName);
?
//数组和集合转换工具类
public class CollectionUtil {
?/**
? ? ?* List集合转换为数组
? ? ?*/
? ? @SuppressWarnings("unchecked")
? ? public static <T> T[] toArray(List<T> items, Class<T> tClass) {
? ? ? ? if (items == null || items.size() == 0)
? ? ? ? ? ? return null;
? ? ? ? int size = items.size();
? ? ? ? try {
? ? ? ? ? ? T[] array = (T[]) Array.newInstance(tClass, size);
? ? ? ? ? ? return items.toArray(array);
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? return null;
? ? ? ? }
? ? }
/**
? ? ?* 数组集合转换为ArrayList集合
? ? ?*/
? ? public static <T> ArrayList<T> toArrayList(T[] items) {
? ? ? ? if (items == null || items.length == 0)
? ? ? ? ? ? return null;
? ? ? ? ArrayList<T> list = new ArrayList<>();
? ? ? ? Collections.addAll(list, items);
? ? ? ? return list;
? ? }
}
2.拼接字符串(集合中拼接)
//使用StringBuffer ,拼接字符串
list<String>listUser = {"张三",“李四”,“王五”}
?StringBuffer namestr = new StringBuffer();
? ? ? ? int i = 0;
? ? ? ? for (Sting user : listUser) {
? ? ? ? ? ? if (i != 0) {
? ? ? ? ? ? ? ? namestr.append(",");
? ? ? ? ? ? }
? ? ? ? ? ? namestr.append(user);
? ? ? ? ? ? i++;
? ? ? ? }
?
cs