Tuesday, 5 September 2017

java - all substrings in a string

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.ArrayList;
import java.util.List;


public class _String {
    /**
     * Print all substrings of a string
     */

    public static List<String> all_substrings_in_a_string(String str) {
        List<String> list = new ArrayList<>();

        char[] chars = str.toCharArray();

        int size = 0;
        while(size++ < chars.length) {
            char[] c = new char[size];
            for (int i = 0; i < chars.length; i++) {
                if(i + c.length <= chars.length) {
                    for (int j = 0; j < c.length; j++) {
                        c[j] = chars[i+j];
                    }
                    list.add(new String(c));
                }
            }
        }
        return list;
    }
}

No comments:

Post a Comment