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ù)組或使用更高效的算法
對于表情符號等特殊字符,可能需要額外處理
方法補充
方法一:
方案設(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");
// 進行字節(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)文章
Spring boot自定義http反饋狀態(tài)碼詳解
這篇文章主要給大家介紹了Spring boot自定義http反饋狀態(tài)碼的相關(guān)資料,文中介紹的非常詳細,對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面跟著小編一起來學(xué)習(xí)學(xué)習(xí)吧。2017-06-06
java數(shù)據(jù)類型轉(zhuǎn)換陷阱包括列表陷阱
這篇文章主要介紹了java數(shù)據(jù)類型轉(zhuǎn)換的一些陷阱,包括基本數(shù)據(jù)類型轉(zhuǎn)換列表陷阱,基本上這一篇就把常見的問題就給大家分享一下2020-10-10
spring @Validated 注解開發(fā)中使用group分組校驗的實現(xiàn)
這篇文章主要介紹了spring @Validated 注解開發(fā)中使用group分組校驗的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05

