按照字节切分字符串(二)

在项目中,移动运营商要求: 发送手机短信,每一条的短信长度不能超过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);

		

		

	}

    

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值