内容带分隔符的字符串分隔处理

我希望使用“;”字符分隔一个字符串的不同部分,如果字符串中包含;,使用\;进行转义,如:
[quote]“aaa;” “b;b” “ccc”[/quote]
这两个字符串连接起来即为:
[quote]aaa\;;b\;b;ccc [/quote]

StringSpliter指定分隔符和转义符,可将这样的字符串分隔出来:


public class StringSpliter {

public static List<String> spliter(String content, char spliter, char escape) {
if (!StringUtils.hasText(content)) {
return Collections.EMPTY_LIST;
} else {
boolean hasPerEscape = false;

List<String> items = Lists.newArrayList();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
if (hasPerEscape) {
sb.append(escape);
hasPerEscape = false;
}
continue;
}

if (c == escape) {
if (hasPerEscape) {
hasPerEscape = false;
sb.append(c);
} else {
hasPerEscape = true;
}
} else if (c == spliter) {
if (hasPerEscape) {
sb.append(c);
hasPerEscape = false;
} else {
if (sb.length() > 0) {
items.add(sb.toString());
sb.delete(0, sb.length());
}
}
} else {
sb.append(c);
}
}
if (sb.length() > 0) {
items.add(sb.toString());
}
return items;
}
}
}


单元测试:

public class StringSpliterTest {

@Test
public void testSplit(){
String str1 = "aa;bb;cc";

List<String> items = StringSpliter.spliter(str1, ';', '\\');
assertNotNull(items);
assertEquals(items.size(), 3);
assertEquals(items.get(0), "aa");
assertEquals(items.get(1),"bb");
assertEquals(items.get(2),"cc");

str1 = ";aa;bb;;;cc;";
items = StringSpliter.spliter(str1, ';', '\\');
assertNotNull(items);
assertEquals(items.size(), 3);
assertEquals(items.get(0), "aa");
assertEquals(items.get(1),"bb");
assertEquals(items.get(2),"cc");

str1 = "a\\;a;bb\\;;\\;cc";
items = StringSpliter.spliter(str1, ';', '\\');
assertNotNull(items);
assertEquals(items.size(), 3);
assertEquals(items.get(0), "a;a");
assertEquals(items.get(1),"bb;");
assertEquals(items.get(2),";cc");

str1 = "\\;;\\;";
items = StringSpliter.spliter(str1, ';', '\\');
assertNotNull(items);
assertEquals(items.size(), 2);
assertEquals(items.get(0), ";");
assertEquals(items.get(1),";");

str1 = ";;;;;";
items = StringSpliter.spliter(str1, ';', '\\');
assertNotNull(items);
assertEquals(items.size(), 0);

str1 = "\\ ; \\ ;";
items = StringSpliter.spliter(str1, ';', '\\');
assertNotNull(items);
assertEquals(items.size(), 2);
assertEquals(items.get(0), "\\");
assertEquals(items.get(1),"\\");

str1 = "aaa";
items = StringSpliter.spliter(str1, ';', '\\');
assertNotNull(items);
assertEquals(items.size(), 1);
assertEquals(items.get(0), "aaa");
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值