在项目中,移动运营商要求: 发送手机短信,每一条的短信长度不能超过70个byte。因此写了一个字符串切割工具,代码示例demo如下。
import java.util.*;
public class SplitStrCn {
// strList : the splited strings
private static List<String> strList = new ArrayList<String>();
/**
*split String by Byte
*@param srcStr: src String will be splited
*@param beginIndex: the beginning index of the string
*@parem length: the byte length of splited String
*@return : the new splited String
*/
public static int splitByByte(String srcStr,int beginIndex,int length)
{
StringBuffer sb = new StringBuffer(length);
int srcLength = srcStr.length();//source string length
int tempLength = 0;//the byte length
for(;beginIndex < srcLength;beginIndex++){
String tempStr = String.valueOf(srcStr.charAt(beginIndex));//string consists of a char
byte[] b = tempStr.getBytes();//the byte length in the tempStr
tempLength += b.length;
if(length>=tempLength){
System.out.println("beginIndex---"+beginIndex);
sb.append(tempStr);
}
else{
break;
}
}
System.out.println("beginIndex---"+beginIndex);
strList.add(sb.toString());
return beginIndex;
}
public static void main (String[] args) {
String str = "我ABC汉D中EF";
System.out.println(str.getBytes().length);
char[] c = str.toCharArray();
System.out.println(c);
//测试上文提供的函数splitByByte(String,int)函数
System.out.println(SplitStrCn.splitByByte(str,6));
//写了个重载函数 splitByByte(String,int,int),返回值为切割后index的位置,index指向下次切割的开始字符
int beginIndex = 0;//切割字符的初始位置
while (beginIndex < str.length()) {
beginIndex = SplitStrCn.splitByByte(str,beginIndex,6);
System.out.println("-----");
}
//切割后的字符串存放在strList中
for(String s : strList)
System.out.println(s);
}
}