入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

JAVA按指定的字节数截取字符串

创建时间:2017-05-19 投稿人: 浏览次数:1595
	/**
	 * 按指定的字节数截取字符串(一个中文字符占3个字节,一个英文字符或数字占1个字节)
	 * @param sourceString 源字符串
	 * @param cutBytes 要截取的字节数
	 * @return
	 */
	public static String cutString(String sourceString, int cutBytes)
	{
		if(sourceString == null || "".equals(sourceString.trim()))
		{
			return "";
		}
		
		int lastIndex = 0;
		boolean stopFlag = false;
		
		int totalBytes = 0;
		for(int i=0; i<sourceString.length(); i++)
		{
			String s = Integer.toBinaryString(sourceString.charAt(i));
			if(s.length() > 8)
			{
				totalBytes += 3;
			}
			else
			{
				totalBytes += 1;
			}
			
			if(!stopFlag)
			{
				if(totalBytes == cutBytes)
				{
					lastIndex = i;
					stopFlag = true;
				}
				else if(totalBytes > cutBytes)
				{
					lastIndex = i - 1;
					stopFlag = true;
				}
			}
		}
		
		if(!stopFlag)
		{
			return sourceString;
		}
		else
		{
			return sourceString.substring(0, lastIndex + 1);
		}
	}

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像