Java字符串按照字节数进行截取

一、问题

编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截半个,如"hi你好啊,joshua317" 4,应该截为"hi你",输入"hi你好啊,joshua317" 8,应该输出“hi,你好”,而不是“hi,你好+啊的半个”。

二、分析

容易产生困惑的是中文字符和英文字符,在这里需要考虑汉字和英文字符的占用字节数问题,中文字符占两个字节,英文字符占一个字节,理解了这个,就很容易实现了。

三、编程

package com.joshua317;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("请输入字符串:");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        System.out.println("请输入字节数:");
        int n = scanner.nextInt();
        interception(string2Array(str), n);
    }

    /**
     * 将字符串转成字符串数组
     * @param string
     * @return
     */
    public static String[] string2Array(String string)
    {
        String[] temp = new String[string.length()];
        for (int i = 0; i < temp.length; i++) {
            temp[i] = string.substring(i,i+1);
        }
        return temp;
    }

    /**
     * 字符串按字节数截取
     * @param str
     * @param n
     */
    public static void interception(String[] str, int n)
    {
        int count = 0;
        String m = "[u4e00-u9fa5]";
        System.out.println("以每" + n +"个字节划分的字符串如下所示:");
        for (int i=0; i < str.length; i++) {
            if (str[i].matches(m)) {
                //如果当前字符是汉子,计数器加2
                count += 2;
            } else {
                //如果当前字符不是是汉子,计数器加1
                count += 1;
            }
            //如果当前计数器的值小于n,则直接输出当前字符
            if (count < n) {
                System.out.print(str[i]);
            } else if (count == n) {
                System.out.print(str[i]);
                count = 0;
                //满足n个字节后,就换行
                System.out.println();
            } else {//如果当前计数器count的值大于n,说明有汉子,换行输出,且此时计数器count=2
                System.out.println();
                System.out.print(str[i]);
                count = 2;
            }
        }
    }
}
 
 
 

 

原文地址:https://www.cnblogs.com/joshua317/p/15460359.html