Creating an array of substrings from a string

I have a string that has no spaces and I wanted to create an array that consists of substrings of a word. For example, let's say the line stackoverflow . The array should look like this:

[sta, cko, ver, flo, w]

The code I am using is below and it only gives me the first item. Any help would be appreciated.

public static ArrayList<String> getWords(String s){
    ArrayList<String> words = new ArrayList<String>();
    for(int i=0;i<s.length(); i=i+3){
        words.add(s.substring(i, 3));
    }
    return words;
}

      

+3


source to share


4 answers


There are two problems with the code. First, "3" in

s.substring(i, 3)

      

means the third index from the beginning of the string, not the third index from i, so you need

s.substring(i, i + 3)

      



Second, if the string is shorter than i + 3, you will get an exception. To fix this problem, you can use Math.min. It will look something like this:

public static ArrayList<String> getWords(String s){
ArrayList<String> words = new ArrayList<String>();
for(int i=0;i<s.length(); i=i+3){
    words.add(s.substring(i, Math.min(i + 3, i.length())));
}
return words;

      

}

+3


source


You need to pass i + 3

as the second parameter to the call substring

(it takes start and end indices). Also, I prefer to program the interface List

. You can use +=

instead i = i + 3

. And you need a sentence else

if String

there are no three letters. How,

public static List<String> getWords(String s) {
    List<String> words = new ArrayList<>();
    for (int i = 0; i < s.length(); i += 3) {
        if (i + 3 < s.length()) {
            words.add(s.substring(i, i + 3));
        } else {
            words.add(s.substring(i));
        }
    }
    return words;
}

      

Then, for completeness, I tested it with a basic method main

like



public static void main(String[] args) {
    System.out.println(getWords("stackoverflow"));
}

      

What are the outputs (on request)

[sta, cko, ver, flo, w]

      

+1


source


You are on the right track, but yours substring

should be (i, i+3)

like this:

public static ArrayList<String> getWords(String s){
    ArrayList<String> words = new ArrayList<String>();
    for(int i=0;i<s.length(); i+=3){
        if (i+3 >= s.length())
            words.add(s.substring(i));
        else
            words.add(s.substring(i, i+3));
    }
    return words;

      

+1


source


You can make it much easier using guava Splitter :

String f = "stackoverflow";
List<String> p = Splitter.fixedLength(3).splitToList(f);
System.out.println(p); // [sta, cko, ver, flo, w]

      

+1


source







All Articles