我想将以下消息除以10个字符。我想将每个部分都附加到StringBuilder对象中。
04421,1,13,S,312|4000004130,1;4000000491,1;4000005240,1;4000005789,2;4000004978,2;4000004934,2;4000004936,1;4000000569,2;4000005400,1;4000000;4000004934,2;
我已经完成了以下解决方案:
if(getMsgOtherPart(message) != null){
System.out.println("part message::"+getMsgOtherPart(message));
String newMessage = getMsgOtherPart(message) ;
int len = newMessage.length();
System.out.println("len::"+len);
int firstIndex = 0;
int limit = 10;
int lastIndex = 10;
int count = 0;
StringBuilder sb = new StringBuilder();
String completeMessage = null;
for(int i = 0; i <= len;i++){
count++;
if( count == limit && lastIndex < len){
sb.append(getSmsUniqueHeader());
sb.append(newMessage.substring(firstIndex,lastIndex));
sb.append("#");
sb.append("\n");
firstIndex = lastIndex;
lastIndex = firstIndex + limit;
count = 0;
} else if(count < limit && i == len) {
System.out.println("lastIndex:: "+lastIndex);
sb.append(getSmsUniqueHeader());
sb.append(newMessage.substring(lastIndex-10));
sb.append("#");
}
}
completeMessage = sb.toString();
System.out.println("message::\n"+completeMessage);
}
我得到了输出:
message::
$04421,1,13#
$,S,312|400#
$0004130,1;#
$4000000491#
$;400000540#
$0,1;400000#
$0;40000000#
$63,1;40000#
$00076,1;40#
$00000776,2#
$;400000078#
$8,2;400000#
------------
$0;#
请让我知道优化我的解决方案。
答案 0 :(得分:2)
我在我的一个项目中做过这种事情,这里是我使用的函数,它返回List但你可以修改它并使用StringBuilder。
public List<String> splitStringEqually(String txtStr, int subStringSize) {
List<String> splittedStringList = new ArrayList<String>();
for (int start = 0; start < txtStr.length(); start += subStringSize) {
splittedStringList.add(txtStr.substring(start, Math.min(txtStr.length(), start + subStringSize)));
}
return splittedStringList;
}
答案 1 :(得分:2)
您可以使用Google的Guava库并使用Splitter类。
StringBuilder sb=new StringBuilder();
for(String s: Splitter.fixedLength(10).split(message)){
sb.append(s);
sb.append("#\n");
}
System.out.println(sb.toString());
答案 2 :(得分:0)
字符串在内部维护为char数组。您可以使用message.toCharArray()
获取该char数组的副本,并使用简单的循环或java 8流选择10块的元素,并执行您需要执行的任何操作。
答案 3 :(得分:0)
严重依赖https://graph.microsoft.io/en-us/docs/authorization/app_authorization并解决来自OP的特定请求,代码可能看起来像这样(请注意那个,请不要这个!):
public String splitStringEqually(String txtStr, int subStringSize) {
// Start off with the header
StringBuilder sb = new StringBuilder("message::\n");
int len = txtStr.length();
for (int start = 0; start < len; start += subStringSize) {
sb.append("$");
// Copy the next 10 characters, or less if at end of string
// Does not use txtStr.substring() as that creates an
// unnecessary temporary string
sb.append(txtStr, start, Math.min(len, start + subStringSize));
sb.append("#\n");
}
return sb.toString();
}
这可以简单地调用:
String completeMessage = splitStringEqually(newMessage, limit);