1. 程式人生 > >JAVA按指定的位元組數擷取字串

JAVA按指定的位元組數擷取字串

	/**
	 * 按指定的位元組數擷取字串(一箇中文字元佔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);
		}
	}