java - 给定一个字符串,生成所有 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!
这个问题会对我有所帮助,但我完全不熟悉红宝石。
解决方案
为此,您不需要两个循环。您可以使用该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
。对于您的方案,这两种方法都可以使用。
推荐阅读
- c# - 如何在异常过滤器范围内获取应用程序库 url?
- mongodb - 在mongodb中进行多次搜索并替换?
- html - 具有基线配置文件和 h264 编码的 Mp4 无法在 chrome 中播放
- beautifulsoup - 仅当标签以简洁的方式存在时才获取标签的字符串值的Beautifulsoup方法?
- html - 使用 div 的“灵活”响应表。如果可以的话,一整列会延伸到哪里
- python - 使用 python 验证 mp3 文件的最佳方法
- r - 将所有列与一列匹配的条件
- umbraco - 将 IContent 转换为 IPublishedContent Umbraco 8
- java - 使用 WS-Security 签署 SOAP 消息
- ios - Xcode 10.2.1:跳转到运算符定义?