Java 给定一个字符串,生成所有2个连续字符、3个连续字符…依此类推,最多生成(str.length()-1个)连续字符

Java 给定一个字符串,生成所有2个连续字符、3个连续字符…依此类推,最多生成(str.length()-1个)连续字符,java,string,combinations,Java,String,Combinations,我需要在Java中完成以下工作: 1.拿一根绳子。 2.生成字符串中的所有2个连续字符。 3.生成字符串中的所有3个连续字符。 4.依此类推,直到最后一代,这将是str.length-1个连续字符。 为了进一步澄清,考虑字符串您好!字符串的长度为6。请注意,上一代是由5个连续字符组成的。输出应为: he // 2-consecutive el // 2-consecutive ll // 2-consecutive lo // 2-consecutive o! // 2-consecutive

我需要在Java中完成以下工作: 1.拿一根绳子。 2.生成字符串中的所有2个连续字符。 3.生成字符串中的所有3个连续字符。 4.依此类推,直到最后一代,这将是str.length-1个连续字符。 为了进一步澄清,考虑字符串您好!字符串的长度为6。请注意,上一代是由5个连续字符组成的。输出应为:

he // 2-consecutive
el // 2-consecutive
ll // 2-consecutive
lo // 2-consecutive
o! // 2-consecutive

hel // 3-consecutive
ell // 3-consecutive
llo // 3-consecutive
lo! // 3-consecutive

hell // 4-consecutive
ello // 4-consecutive
llo! // 4-consecutive

hello // 5-consecutive
ello! // 5-consecutive
这就是我所尝试的:

String str=hello!; int len=str.length;
对于int set=2;设置此操作不需要两个循环。您可以使用substring属性。如果你真的想使用另一个循环,你当然可以用一个循环替换子字符串,就像你的答案一样,还有一个简单的If条件来确保我们没有超过输入的最后一个索引

    String str = "hello!";
    int len = str.length();
    int gap = 2; // This determines the consecutive character size.
    for( int set = 0; set <= len; set++ )
    {
        if( ( set + gap ) <= len )
        {
            String subString = str.substring( set, set + gap );
            System.out.println( subString );
        }
    }

如果在循环中使用字符串连接。请记住,不建议这样做。改用StringBuilder。对于您的场景,这两种方法都会起作用。

只是想指出,您的原始代码非常接近正确。此版本可产生所需的结果:

String str = "hello!";
int len = str.length();
for (int set = 2; set <= (len - 1); set++) {
    for (int n = 0; n <= (len - set); n++) {     // changed (len - i) to (len-set)
        for (int k = 0; k < set; k++) {          // changed (k <= n)  to (k < set)
            System.out.print(str.charAt(n+k));   // changed (k)       to (n+k)
        }
        System.out.println();
    }
}
根据Klaus的建议,您还可以使用子字符串:

for(int set = 2; set < len; set++) {
    for(int n=0; n <= len-set; n++) {
        System.out.println(str.substring(n, n+set));
    }
}

非常感谢。工作起来很有魅力。我正在通读这本书以获得充分的理解。令人惊叹的谢谢你。非常感谢您的反馈。
String str = "hello!";
int len = str.length();
for (int set = 2; set <= (len - 1); set++) {
    for (int n = 0; n <= (len - set); n++) {     // changed (len - i) to (len-set)
        for (int k = 0; k < set; k++) {          // changed (k <= n)  to (k < set)
            System.out.print(str.charAt(n+k));   // changed (k)       to (n+k)
        }
        System.out.println();
    }
}
for(int set = 2; set < len; set++) {
    for(int n=0; n <= len-set; n++) {
        System.out.println(str.substring(n, n+set));
    }
}