Juan Giacosa
Juan Giacosa

Reputation: 194

In java, how can I check how many substrings of length n are within a given string S?

I'm writing a program where I have to compare all possible substrings of size 'k' contained within a given string 's', and then order them in a lexicographic way so smaller substrings are first and larger are last.

Example: s = "serendipia" k = 3 Should result in ["ser", "ere", "ren", "end","ndi", "dip", "ipi", "pia" ]

I'm given 's'(String) and 'k' (size of substring), and this is what I came up with at first:

for (int i = 0; i < s.length(); i++){
        substringsArray[i] = s.substring(i,i+k); 
        //System.out.format("%s %d %d%n",substringsArray[i], i, s.length());
    }

Thought this would work since worst case scenario 'k' == 1 and I'll have as many letters inside my array as s.length()-1. It indeed works but I'm getting an obvious exception: IndexOutOfBoundsException

I've also tried using ArrayList insted of an Array so I get a dynamic size list, but the same problem arose again: How do I know how many times do I have to iterate over the string without going out of bounds?

So I'm wondering, is there a way/algorithm that could help me figure out- given 's' and 'k' - the correct size of my array?

Upvotes: 0

Views: 465

Answers (1)

Juan Carlos Mendoza
Juan Carlos Mendoza

Reputation: 5794

Try this:

// make sure you don't go beyond the String's length
for (int i = 0; (i+k) <= s.length(); i++){    
    substringsArray[i] = s.substring(i,i+k);
}

DEMO

Upvotes: 2

Related Questions