乐者为王

Do one thing, and do it well.

短信分拆算法

今天,突然心血来潮,写了一段分拆短信的代码。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class SMSHelper {
    private static final int SMS_MAX_LENGTH = 70;

    public static List split(String msg) {
        if (msg.length() <= SMS_MAX_LENGTH) {
            throw new IllegalArgumentException("被分拆的短信长度必须大于70个字符");
        }

        List<String> list = new ArrayList<String>();
        int i = 0, start = 0;
        while (true) {
            i++;
            String prompt = "(第" + i + "条)";
            int remain = SMS_MAX_LENGTH - prompt.length();
            if (start + remain > msg.length()) {
                list.add(prompt + msg.substring(start));
                break;
            }
            list.add(prompt + msg.substring(start, start + remain));
            start += remain;
        }
        return list;
    }
}

Comments