[英]Given a string, generate all 2-consecutive characters, 3-consecutive characters…and so on up to ( str.length()-1 )-consecutive characters
我需要在 Java 中完成以下操作:
1.取一根绳子。
2. 生成字符串中所有 2 个连续的字符。
3. 生成字符串中所有 3 个连续的字符。
4. 以此类推,直到最后一代,这将是 (str.length())-1-连续字符。
为了进一步澄清,请考虑字符串hello!
. 该字符串的长度为6
。 注意最后一代是 5 个连续的字符。 output 应该是:
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();
}
}
代码给出了以下 output,这与我之前所希望的完全不同:
h
he
hel
hell
hello
hello!
h
he
hel
hell
hello
hello!
h
he
hel
hell
hello
hello!
h
he
hel
hell
hello
hello!
这个问题会对我有所帮助,但我完全不熟悉 ruby。
为此,您不需要两个循环。 您可以使用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 );
}
}
如果您在循环中使用字符串连接。 请记住,不建议这样做。 请改用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 的建议,您还可以使用 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ:
for(int set = 2; set < len; set++) {
for(int n=0; n <= len-set; n++) {
System.out.println(str.substring(n, n+set));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.