字符串多条件分割

实现原理:

1、将分割条件放在集合中

2、利用Math类的Random生成指定长度的字符串作为唯一标识分割符

3、for循环操作获取集合中的元素,在被分割字符串中利用replace方法在字符串中查找集合中的元素,并替换成唯一标识分隔符+集合元素。产生新的带有分隔符的字符串。

4、调用String类的split方法将字符串分割,存放在String类型的数组中。


package com.test;


import java.util.ArrayList;
import java.util.Iterator;


public class SplitStringMultiCondition {


//生成随机产生的6位数
public static String getUnique(){
String unique="";
String[] str=new String[]{"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
for(int i=0;i<6;i++){
int round = (int) Math.round(Math.random()*26);
unique+=str[round];
}
return unique;
}

// 在每个条件前面插入一个唯一标识
public static String test(ArrayList<String> arrayList,String data,String unique){
while(data.indexOf(unique)>-1){
unique=getUnique();
}
Iterator<String> iterator = arrayList.iterator();
while (iterator.hasNext()) {
String  s = (String) iterator.next();
if(data.indexOf(s)>-1){
data=data.replace(s, unique+s);
}

}
return data;
}

public static void main(String[] args) {
String data="个人信息 姓名:张三;年龄:25";
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("姓名");
arrayList.add("年龄");
String unique = getUnique();
String test = test(arrayList, data,unique);
String[] split = test.split(unique);
for (int i = 0; i < split.length; i++) {
System.out.println(split[i]);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值