首页 > 解决方案 > 给定一个字符串,生成所有 2 个连续的字符、3 个连续的字符……等等直到 ( str.length()-1 ) 个连续的字符

问题描述

我需要在 Java 中完成以下工作:

1. 取一个字符串。

2. 生成字符串中所有 2 个连续的字符。

3. 生成字符串中所有 3 个连续的字符。

4. 以此类推,直到最后一代,这将是 (str.length())-1-连续字符。

为了进一步澄清,请考虑 string hello!。字符串有长度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();
            for (int set = 2; set <= (len-1); set++) {
            for (int n = 0; n <= (len-1); n++) {
                for (int k = 0; k <= n; k++) {
                    System.out.print(str.charAt(k));
                    }
                    System.out.println();
                }
}

该代码给出了以下输出,这与我之前所希望的完全不同:

h
he
hel
hell
hello
hello!
h
he
hel
hell
hello
hello!
h
he
hel
hell
hello
hello!
h
he
hel
hell
hello
hello!

这个问题会对我有所帮助,但我完全不熟悉红宝石。

标签: javastringcombinations

解决方案


为此,您不需要两个循环。您可以使用该substring物业。如果你真的想使用另一个循环,你当然可以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 );
        }
    }

这就是您可以使用第二个循环而不是substring

    for( int set = 0; set <= len; set++ )
    {
        if( ( set + gap ) <= len )
        {
            String result = "";
            for( int i = set; i < set + gap; i++ )
            {
                result += str.charAt( i );
            }
            System.out.println( result );
        }
    }

如果您在循环中使用字符串连接。请记住,不建议这样做。改用 a StringBuilder。对于您的方案,这两种方法都可以使用。


推荐阅读