Java實現(xiàn)按字節(jié)長度截取字符串
在Java中,由于字符串可能包含多字節(jié)字符(如中文),直接按字節(jié)長度截取可能會導(dǎo)致亂碼或截取不準(zhǔn)確的問題。以下是幾種按字節(jié)長度截取字符串的方法:
方法一:使用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;
}
// 處理截斷可能導(dǎo)致的半個字符問題
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();
}
}
注意事項
不同編碼下字符占用的字節(jié)數(shù)不同:
UTF-8編碼中,中文通常占3字節(jié)
GBK編碼中,中文占2字節(jié)
ISO-8859-1編碼中,所有字符占1字節(jié)
截取時需要考慮編碼的字節(jié)邊界,避免截斷多字節(jié)字符導(dǎo)致亂碼
性能考慮:對于大字符串頻繁截取,建議緩存字節(jié)數(shù)組或使用更高效的算法
對于表情符號等特殊字符,可能需要額外處理
方法補(bǔ)充
方法一:
方案設(shè)計
1. 字節(jié)長度計算
首先,我們需要計算字符串的字節(jié)長度。在Java中,可以使用String.getBytes()方法將字符串轉(zhuǎn)換為字節(jié)數(shù)組,然后計算數(shù)組的長度。
2. 截取邏輯
根據(jù)提供的字節(jié)長度,我們需要從字符串的開始位置截取到指定的字節(jié)長度。如果截取后的字符串在字符邊界上,我們需要確保截取后的字符串是有效的UTF-8序列。
3. 異常處理
在截取過程中,可能會遇到無效的UTF-8序列,我們需要捕獲并處理這些異常。
代碼實現(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) {
// 處理無效的UTF-8序列
return cutByByteLength(input, byteLength - 1);
}
}
}方法二:
完整代碼
public class SubstringDemo {
public static void main(String[] args) {
// 輸入待截取的字符串和截取長度
String str = "這是一個測試字符串";
int length = 5; // 需要截取的字節(jié)長度
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實現(xiàn)按字節(jié)長度截取字符串的文章就介紹到這了,更多相關(guān)Java截取字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決IntelliJ IDEA中鼠標(biāo)拖動選擇為矩形區(qū)域問題
這篇文章主要介紹了解決IntelliJ IDEA中鼠標(biāo)拖動選擇為矩形區(qū)域問題,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
SpringBoot 統(tǒng)一異常處理的實現(xiàn)示例
本文主要介紹了SpringBoot 統(tǒng)一異常處理的實現(xiàn)示例,目的就是在異常發(fā)生時,盡可能地減少破壞,下面就來介紹一下,感興趣的可以了解一下2024-07-07
SpringBoot整合SpringSecurity認(rèn)證與授權(quán)
在項目開發(fā)中,權(quán)限認(rèn)證是很重要的,尤其是一些管理類的系統(tǒng),對于權(quán)限要求更為嚴(yán)格,本文主要介紹了SpringBoot整合SpringSecurity認(rèn)證與授權(quán),感興趣的可以了解一下2023-11-11
配置pom.xml用maven打包java工程的方法(推薦)
下面小編就為大家?guī)硪黄渲胮om.xml用maven打包java工程的方法(推薦)。小編覺得挺不錯的, 現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06
SpringBoot和Vue2項目配置https協(xié)議過程
本文詳細(xì)介紹了SpringBoot項目和Vue2項目的部署流程及SSL證書配置,對于SpringBoot項目,需將.pfx文件放入resources目錄并配置server,然后打包部署,Vue2項目中,涉及檢查nginx的SSL模塊、編譯新的nginx文件2024-10-10

