SMS Splitting

Sort by

recency

|

1 Discussion

|

  • + 0 comments
        public static List<String> segments(String message) {
            int messageLength = message.length();
            List<String> segments = new ArrayList<>();
    
            if (messageLength <= maxSegmentChars) {
                segments.add(message);
            } else {
                int totalSegments = (int) Math.ceil((double) messageLength / (maxSegmentChars - 5));
    
                for (int i = 1; i <= totalSegments; i++) {
                    for (int j = 155; j >= 0; j--) {
                        if (messageLength <= 155) {
                            String segment = message + "(%s/%s)".formatted(i, totalSegments);
                            segments.add(segment);
    
                            break;
                        } else if (' ' == message.charAt(j)) {
                            int last = j == 155 ? j : j + 1;
                            String segment = message.substring(0, last) + "(%s/%s)".formatted(i, totalSegments);
                            segments.add(segment);
    
                            message = message.substring(last);
                            messageLength = message.length();
    
                            break;
                        }
                    }
                }
            }
    
            return segments;
            }
    
    }
    

No more comments