开发者

Java实现按字节长度截取字符串

目录
  • 方法一:使用String的getBytes方法
  • 方法二:指定字符编码处理
  • 方法三:更精确的字符编码处理
  • 使用示例
  • 注意事项
  • 方法补充

在Java中,由于字符串可能包含多字节字符(如中文),直接按字节长度截取可能会导致乱码或截取不准确的问题。以下是几种按字节长度截取字符串的方法:

方法一:使用String的getBytes方法

public static String substringByBytes(String str, int byteLength) {
    if (sthttp://www.devze.comr == null || str.isEmpty() || byteLength <= 0) {
        return "";
    }
    
    byte[] bytes = str.getBytes();
    if (byteLength >= bytes.length) {
        return str;
    }
    
    // 处理截取位置可能是多字节字符的情况
    int len = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        len += (c <= 255) ? 1 : 2; // 假设非ASCII字符占2字节
        
        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;
    }
    
    // 根据编码创建新的字符串
    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;
    }
    
    // 处理截断可能导致的半个字符问题
    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 Woandroidrld!";
    
    try {
        System.out.printlnwjvbsEWb(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();
    }
}

注意事项

不同编码下字符占用的字节数不同:

UTF-8编码中,中文通常占3字节

GBK编码中,中文占2字节

ISO-8859-1编码中,所有字符占1字节

截取时需要考虑编码的字节边界,避免javascript截断多字节字符导致乱码

性能考虑:对于大字符串频繁截取,建议缓存字节数组或使用更高效的算法

对于表情符号等特殊字符,可能需要额外处理

方法补充

方法一:

方案设计

1. 字节长度计算

首先,我们需要计算字符串的字节长度。在Java中,可以使用String.getBytes()方法将字符串转换为字节数组,然后计算数组的长度。

2. 截取逻辑

根据提供的字节长度,我们需要从字符串的开始位置截取到指定的字节长度。如果截取后的字符串在字符边界上,我们需要确保截取后的字符串是有效的UTF-8序列。

3. 异常处理

在截取过程中,可能会遇到无效的UTF-8序列,我们需要捕获并处理这些异常。

代码实现

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; // 需要截取的字节长度

        try {
            // 将字符串转换为字节数组
            byte[] bytes = str.getBytes("UTF-8");
            
            // 进行字节截取
            String result = new String(bytes, 0, length, "UTF-8");

            // 输出截取后的结果
            System.out.println("截取后的结果为:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

到此这篇关于Java实现按字节长度截取字符串的文章就介绍到这了,更多相关Java截取字符串内容请搜索编程客栈(www.devze.com)以前的文章或php继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜