我有一种情况,我必须拆分一个字符串(具有逗号分隔的值),以限制字符串中的最大字符数,同时保持逗号分隔的格式。
例如String str = "test,et,ste,ts,tst,est,ste,tstete,sts,tet,estst,tet"
说一个字符串中的最大字符数可以是10。那么我的输出应该是:
test,et (7 chars)
ste,ts,tst (10 chars)
est,ste (7 chars)
tstete,sts (10 chars)
tet,estst (9 chars)
tet (3 chars)
基本上,输出将被循环并附加到查询中的IN子句中,但IN子句只能处理(最大字符数),因此请分割字符串(含义是用逗号分隔的完整值),以防长度的字符串超出限制。
答案 0 :(得分:0)
您可以执行以下操作(查看注释以进行解释):
public static void main(String[] args) {
String str = "test,et,ste,ts,tst,est,ste,tstete,sts,tet,estst,tet";
// Split it first
String words[] = str.split(",");
// Use a buffer
StringBuffer sb = new StringBuffer("");
List<String> result = new ArrayList<>();
String delim = "";
// Iterate through the words.
for(int i = 0; i< words.length; i++) {
// You will add the comma so total length should be less
// than 10.
if(sb.length() + words[i].length() < 10) {
sb.append(delim);
sb.append(words[i]);
delim = ",";
}
else {
delim = "";
result.add(sb.toString());
System.out.println(sb.toString());
sb = new StringBuffer(words[i]);
delim = ",";
}
}
// Print to check the results
for(String s: result) {
System.out.println(s);
}
}
答案 1 :(得分:0)
此任务是一项棘手的任务-以下lambda表达式可以解决该问题
comma = false; // class boolean variable
last = 0; // class int variable
Stream.of( str.split( "," ) ).collect(
Collector.of( () -> new StringBuilder(),
(buf, s) -> {
if( buf.length() - last + s.length() < 10 ) {
buf.append( comma ? "," : "" ).append( s );
comma = true;
}
else {
int len = buf.length();
buf.append( " (" ).append( len - last ).append( " chars)\n" );
last = buf.length();
buf.append( s );
}
},
(buf1, buf2) -> null, // unused
buf -> {
int len = buf.length();
return( buf.append( " (" ).append( len - last ).append( " chars)\n" ).toString() );
} ) );
,并且没有(...字符)解释:
Stream.of( str.split( "," ) ).collect(
Collector.of( () -> new StringBuilder(),
(buf, s) -> {
if( buf.length() - last + s.length() < 10 ) {
buf.append( comma ? "," : "" ).append( s );
comma = true;
}
else {
buf.append( '\n' );
last = buf.length();
buf.append( s );
}
},
(buf1, buf2) -> null, // unused
buf -> {
return( buf.append( '\n' ).toString() );
} ) );
所需的输出作为字符串返回……
答案 2 :(得分:-1)
我会这样做:
arr[]
out = ""
for(int i = 0; i< arr.length; i++)
if (out.length + arr[i].length < 10) {out += ","+arr[i];} else {print out; out = "";}
也许我忘记了什么...但是你应该明白这个主意吧?