字符串按照固定长度分割并存储在数组

导读:本篇文章讲解 字符串按照固定长度分割并存储在数组,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

测试代码:

public class Test {
    public static void main(String[] args) {
        String data = "de0c0c294e31";
        String[] strings = splitStringByLength(data, 4);
        for (int i = 0; i < strings.length; i++) {
            System.out.println(strings[i]);
        }

    }

    public static String[] splitStringByLength(String src, int length) {
        //检查参数是否合法
        if (null == src || src.equals("")) {
            System.out.println("the string is null");
            return null;
        }

        if (length <= 0) {
            System.out.println("the length < 0");
            return null;
        }

        System.out.println("now split \"" + src + "\" by length " + length);

        int n = (src.length() + length - 1) / length; //获取整个字符串可以被切割成字符子串的个数

        String[] split = new String[n];

        for (int i = 0; i < n; i++) {
            if (i < (n - 1)) {
                split[i] = src.substring(i * length, (i + 1) * length);
            } else {
                split[i] = src.substring(i * length);
            }
        }

        return split;
    }
}

测试结果:

de0c
0c29
4e31

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119806.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!