package java_programs;
import java.util.*;

public class WRAP {
    public static void main(String[] args) {
        System.out.println("abc".lastIndexOf("c", 30));
        List<String> results = wrap("This is an example of a wrap function implementation in Java. It should wrap the text into lines.", 20);
        for (String line : results) {
            System.out.println(line);
        }
    }

    public static ArrayList<String> wrap(String text, int cols) {
        ArrayList<String> lines = new ArrayList<String>();

        String line;
        while (text.length() > cols) {
            int end = text.lastIndexOf(" ", cols);
            if (end == -1) {
                end = cols;
            }
            line = text.substring(0, end);
            text = text.substring(end).trim();
            lines.add(line);
        }
        
        if (!text.isEmpty()) {
            lines.add(text);
        }

        return lines;
    }
}