Java實(shí)現(xiàn)按字節(jié)長(zhǎng)度截取字符串
在Java中,由于字符串可能包含多字節(jié)字符(如中文),直接按字節(jié)長(zhǎng)度截取可能會(huì)導(dǎo)致亂碼或截取不準(zhǔn)確的問(wèn)題。以下是幾種按字節(jié)長(zhǎng)度截取字符串的方法:
方法一:使用String的getBytes方法
public static String substringByBytes(String str, int byteLength) { if (str == null || str.isEmpty() || byteLength <= 0) { return ""; } byte[] bytes = str.getBytes(); if (byteLength >= bytes.length) { return str; } // 處理截取位置可能是多字節(jié)字符的情況 int len = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); len += (c <= 255) ? 1 : 2; // 假設(shè)非ASCII字符占2字節(jié) if (len > byteLength) { return str.substring(0, i); } else if (len == byteLength) { return str.substring(0, i + 1); } } return str; }
方法二:指定字符編碼處理
public static String substringByBytes(String str, int byteLength, String charsetName) throws UnsupportedEncodingException { if (str == null || str.isEmpty() || byteLength <= 0) { return ""; } byte[] bytes = str.getBytes(charsetName); if (byteLength >= bytes.length) { return str; } // 根據(jù)編碼創(chuàng)建新的字符串 return new String(bytes, 0, byteLength, charsetName); }
方法三:更精確的字符編碼處理
public static String substringByBytes(String str, int maxBytes, String charsetName) throws UnsupportedEncodingException { if (str == null || charsetName == null || charsetName.isEmpty()) { return str; } byte[] bytes = str.getBytes(charsetName); if (bytes.length <= maxBytes) { return str; } // 處理截?cái)嗫赡軐?dǎo)致的半個(gè)字符問(wèn)題 int nBytes = 0; int i = 0; for (; i < str.length(); i++) { char c = str.charAt(i); int charBytes = String.valueOf(c).getBytes(charsetName).length; if (nBytes + charBytes > maxBytes) { break; } nBytes += charBytes; } return str.substring(0, i); }
使用示例
public static void main(String[] args) { String testStr = "你好,Java世界!Hello World!"; try { System.out.println(substringByBytes(testStr, 10)); // 輸出:你好,J System.out.println(substringByBytes(testStr, 15, "UTF-8")); // 輸出:你好,Java System.out.println(substringByBytes(testStr, 20, "GBK")); // 輸出:你好,Java世界! } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
注意事項(xiàng)
不同編碼下字符占用的字節(jié)數(shù)不同:
UTF-8編碼中,中文通常占3字節(jié)
GBK編碼中,中文占2字節(jié)
ISO-8859-1編碼中,所有字符占1字節(jié)
截取時(shí)需要考慮編碼的字節(jié)邊界,避免截?cái)喽嘧止?jié)字符導(dǎo)致亂碼
性能考慮:對(duì)于大字符串頻繁截取,建議緩存字節(jié)數(shù)組或使用更高效的算法
對(duì)于表情符號(hào)等特殊字符,可能需要額外處理
方法補(bǔ)充
方法一:
方案設(shè)計(jì)
1. 字節(jié)長(zhǎng)度計(jì)算
首先,我們需要計(jì)算字符串的字節(jié)長(zhǎng)度。在Java中,可以使用String.getBytes()
方法將字符串轉(zhuǎn)換為字節(jié)數(shù)組,然后計(jì)算數(shù)組的長(zhǎng)度。
2. 截取邏輯
根據(jù)提供的字節(jié)長(zhǎng)度,我們需要從字符串的開(kāi)始位置截取到指定的字節(jié)長(zhǎng)度。如果截取后的字符串在字符邊界上,我們需要確保截取后的字符串是有效的UTF-8序列。
3. 異常處理
在截取過(guò)程中,可能會(huì)遇到無(wú)效的UTF-8序列,我們需要捕獲并處理這些異常。
代碼實(shí)現(xiàn)
public class ByteLengthStringCutter { public static String cutByByteLength(String input, int byteLength) { if (input == null || byteLength <= 0) { return ""; } byte[] bytes = input.getBytes(StandardCharsets.UTF_8); if (bytes.length <= byteLength) { return input; } StringBuilder sb = new StringBuilder(); try { for (int i = 0; i < byteLength; i++) { sb.append((char) bytes[i]); } return sb.toString(); } catch (IllegalArgumentException e) { // 處理無(wú)效的UTF-8序列 return cutByByteLength(input, byteLength - 1); } } }
方法二:
完整代碼
public class SubstringDemo { public static void main(String[] args) { // 輸入待截取的字符串和截取長(zhǎng)度 String str = "這是一個(gè)測(cè)試字符串"; int length = 5; // 需要截取的字節(jié)長(zhǎng)度 try { // 將字符串轉(zhuǎn)換為字節(jié)數(shù)組 byte[] bytes = str.getBytes("UTF-8"); // 進(jìn)行字節(jié)截取 String result = new String(bytes, 0, length, "UTF-8"); // 輸出截取后的結(jié)果 System.out.println("截取后的結(jié)果為:" + result); } catch (Exception e) { e.printStackTrace(); } } }
到此這篇關(guān)于Java實(shí)現(xiàn)按字節(jié)長(zhǎng)度截取字符串的文章就介紹到這了,更多相關(guān)Java截取字符串內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring boot自定義http反饋狀態(tài)碼詳解
這篇文章主要給大家介紹了Spring boot自定義http反饋狀態(tài)碼的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編一起來(lái)學(xué)習(xí)學(xué)習(xí)吧。2017-06-06java數(shù)據(jù)類型轉(zhuǎn)換陷阱包括列表陷阱
這篇文章主要介紹了java數(shù)據(jù)類型轉(zhuǎn)換的一些陷阱,包括基本數(shù)據(jù)類型轉(zhuǎn)換列表陷阱,基本上這一篇就把常見(jiàn)的問(wèn)題就給大家分享一下2020-10-10spring @Validated 注解開(kāi)發(fā)中使用group分組校驗(yàn)的實(shí)現(xiàn)
這篇文章主要介紹了spring @Validated 注解開(kāi)發(fā)中使用group分組校驗(yàn)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05