1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【備忘】Apexで文字バイト数をチェックして特定バイト数で切り捨てる

Posted at

パターン①

midで1文字ずつ分割してチェックする


public static String biteCheck1 (String targetStr, Integer maxLength) {
    List<String> resultList = new List<String>();
    String result = '';

    String str = '';
    Integer j = 0;
    for (Integer i = 0; i < targetStr.length(); i++) {
        str = targetStr.mid(i,1);
        j += Blob.valueOf(str).size();
        if (j <= maxLength) {
            resultList.add(str);
        } else {
            break;
        }
    }

    for (String s : resultList) result += s;
    system.debug(Blob.valueOf(result).size());
    system.debug(result);
    return result;
}

パターン②

split('')で分割してチェックする

public static String biteCheck2 (String targetStr, Integer maxLength) {
    List<String> splitList = targetStr.split('');
    String result = '';
    List<String> resultList = new List<String>();
    Integer j = 0;
    for (String s : splitList) {
        j += Blob.valueOf(s).size();
        if (j <= maxLength) {
            resultList.add(s);
        } else {
            break;
        }
    }

    for (String s : resultList) result += s;
    system.debug(Blob.valueOf(result).size());
    system.debug(result);
    return result;
}

実行結果
image.png

1
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?