Reputation: 3057
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;
}
Upvotes: 3
Views: 78
Reputation: 73241
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]
Upvotes: 1
Reputation: 383
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;
}
Upvotes: 3
Reputation: 5613
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;
Upvotes: 1
Reputation: 201447
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]
Upvotes: 1