Search code examples
javasubstring

creating a substring of three from a string "welcome"


I'm new to the Java world and I came across a problem. Please have a look and help me in this case.

I have taken a string as "welcome" and I need to store the substrings of 3. And I'm expecting the elements as "wel", "elc", "lco", "com", "ome", "mew", "ewe".

And I'm getting the output as wel elc lco com ome null null

I didn't understand how to iterate for the last two elements.

String string = "welcome";
String stringArray[] = new String[string.length()];
for (int j = 0; j < string.length() - 2; j++) {
    stringArray[j] = string.substring(j, j + 3);
}

for (String d : stringArray)
    System.out.println(d);

I have tried this. Can anyone please help in this. Thankyou.


Solution

  • You cannot archieve that using substring() method, because substring(int beginIndex, int endIndex) yields only characters that are in range of <beginIndex; endIndex). So the endIndex must be greater then beginIndex.

    For example "welcome".substring(3,6); would yield "com", because "c" is at index "3" of "welcome" string (remember that we are counting from "0"), and the "m" is before the index "6" (because the endIndex is exclusive, as the docs says):

    Params:
    beginIndex – the beginning index, inclusive. 
    endIndex – the ending index, exclusive.
    

    Instead, you should travel letter by letter and collect the letters using modulo operation. For example like this:

    String string = "welcome";
    int substringLength = 3;
    String[] stringArray = new String[string.length()];
    
    for (int j = 0; j < string.length(); j++) {
        StringBuilder substringBuilder = new StringBuilder();
        for (int i = 0; i < substringLength; i++) {
            substringBuilder.append(string.charAt((j + i) % string.length()));
        }
        stringArray[j] = substringBuilder.toString();
    }
    
    for (String d : stringArray) {
        System.out.println(d);
    }