简体   繁体   中英

Creating substrings array from a string

I have a string that has no spaces and I wanted to create an array that consists of the substrings of the word. For instance, let the string is stackoverflow The array should be like:

[sta, cko, ver, flo, w]

The code that I use is below and that does give me only the first item. Any help will 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;
}

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

s.substring(i, 3)

means the 3rd index from the beginning of the string, not the 3rd index from i, so you'd want

s.substring(i, i + 3)

Second, if the string is shorter than i + 3, you'll get an exception. To solve this, you can use Math.min. It would 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;

}

You need to pass i + 3 as the second parameter of the substring call (it takes begin and end indexes). Also, I would prefer to program to the List interface. You might use += instead of i = i + 3 . And you need an else clause for when there aren't three letters in the String . Like,

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 main method like

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

Which outputs (as requested)

[sta, cko, ver, flo, w]

You are on the right track, but your substring should be (i, i+3) as the following:

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;

You can ease it significantly by using guava's Splitter :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM