LoginSignup
2
3

More than 5 years have passed since last update.

文字列を長さで分割

Last updated at Posted at 2015-09-02

普通にsubstringを使った場合。これだとサロゲートペアに対応していないので、文字列に「𠮷」などが含まれる場合は文字数が少なくなったり文字化けするなどの不具合が発生する。

public static List<String> splitByLength(String s, int length) {
    List<String> list = new ArrayList<>();
    while (s != null && s.length() != 0) {
        int endIndex = Math.min(length, s.length());
        list.add(s.substring(0, endIndex));
        s = s.substring(endIndex);
    }
    return list;
}

正規表現を使って分割する方法。こちらはサロゲートペア対応。
情報提供:macoshita

public static List<String> splitByLength(String s, int length) {
    List<String> list = new ArrayList<>();
    if (!Strings.isNullOrEmpty(s)) {
        Matcher m = Pattern.compile("[\\s\\S]{1," + length + "}").matcher(s);
        while (m.find()) {
            list.add(m.group());
        }
    }
    return list;
}
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3