java截取字符串中字節長度【轉】

public static String subStr(String str, int subSLength)    { 
		    String  subStr ="";
		    try {
		       if (str == null) return "";    
		       else{   
	                int tempSubLength = subSLength;//截取字節數  
	                 subStr = str.substring(0, str.length()<subSLength ? str.length() : subSLength);//截取的子串    
	                int subStrByetsL = subStr.getBytes("GBK").length;//截取子串的字節長度     
	                // 說明截取的字符串中包含有漢字    
	                while (subStrByetsL > tempSubLength){    
	                    int subSLengthTemp = --subSLength;  
	                    subStr = str.substring(0, subSLengthTemp>str.length() ? str.length() : subSLengthTemp);    
	                    subStrByetsL = subStr.getBytes("GBK").length;    
	                }    
	            }  
		    } catch (Exception e) {
		    	System.out.println(e.getMessage());
		    }
		    return subStr;   
		 }

 

public static void main(String[] args) {
			String name = "踩踩踩12411測114測";
			System.out.println("字符串長度"+name.length());
			System.out.println("截取字符串前10個字節的結果"+subStr(name,10));
		}

 

 結果:java

原字符串值:踩踩踩12411測114測
字符串長度:13
截取字符串前10個字節的結果:踩踩踩1241
相關文章
相關標籤/搜索