该任务要求给定一个字符串,它应该打印出按长度排序的所有可能的子字符串。 例如,如果输入很有趣,它应该打印
funny
funn
unny
fun
unn
nny
...
f
u
n
n
y
这是我的代码
public static void main( String[] args)
{
Scanner scan = new Scanner( System.in);
// constants
// variables
String input;
// program code
input = scan.nextLine();
for ( int i = 0; i < input.length(); i++ )
{
for ( int j = i + 1 ; j <= input.length(); j++ )
{
System.out.println( input.substring( i , j ) );
}
}
}
程序打印出所有可能的子字符串,但不按长度排序。我找不到对子字符串进行排序的方法。不幸的是,我只能使用“do while”或“for”循环,不能使用数组。
我对编程比较陌生,所以如果您能解释一下您的建议,我将非常感激。谢谢
最佳答案
如何按长度顺序打印子字符串
在此示例中,测试字符串将为 abc
。
第一次打印长度为3
abc
--- abc (0,3)
然后打印长度为2的部分:
abc
-- ab (0,2)
-- bc (1,3)
最后打印节长度为1,因此打印:
abc
- a (0,1)
- b (1,2)
- c (2,3)
这样字符串就会按长度顺序打印
如何实现
在伪代码中,这将是:
FOR length in size..1
FOR start in 0..(size-length)
print(substring(start, start+length)
在 Java 中,这将是:
public class Example {
public static void main(final String... args) {
String input = new Scanner(System.in).nextLine();
for (int length = input.length(); length > 0; length--) {
for (int start = 0; start <= (input.length()-length); start++) {
System.out.println(input.substring(start, start+length));
}
}
}
}
关于java - 打印按长度排序的字符串的所有可能的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49264774/