Question

For example, i have a string: "abcdefgh"

and i want it to output that one sting into three letter substrings so it becomes:

"abc"
"bcd"
"cde"
"def"
"efg"
"fgh"
"gha"
"hab"

I currently have the code:

      for (*length of string*){
      (str.substring(i,i+2));

This is with I being the counter of the string.

That being said, how will i make it so that it treats the string as circular so that i can get the sub strings "GHA" and "HAB"?

Thanks

Was it helpful?

Solution

Just try with:

int length = 3;
String input = "abcdefgh";
String circural = input + input.substring(0, length - 1);

for (int i = 0; i < input.length(); i++) {
    String part = circural.substring(i, i + length);
    System.out.println(part);
}

Output:

abc
bcd
cde
def
efg
fgh
gha
hab
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top