打印子串

时间:2013-04-05 04:11:24

标签: java string

然而,我也打印出一个单词的所有子串;我无法得到最后的输出。

import java.util.Scanner;

public class printer {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a word");
        String s = scan.nextLine();
        int i;
        int j;
        for (i=1; i<s.length(); i++) {
            for (j=0; j+i<=s.length(); j++) {
                String ss = s.substring(j, j+i);
                System.out.println(ss);
        } }
    }
}

输入

thunder

输出

t
h
u
n
d
e
r
th
hu
un
nd
de
er
thu
hun
und
nde
der
thun
hund
unde
nder
thunde
hunder
(missing thunder)

当然我只是放了一个System.out.println(s);最后,但我希望它完成for循环

4 个答案:

答案 0 :(得分:8)

将外部for循环条件更改为i<=s.length

答案 1 :(得分:6)

将您在for上迭代的第一个i循环中的检查更改为: -

for (i = 1; i <= s.length(); i++) // "i" should be less than or equal to the length of "s"

答案 2 :(得分:1)

你需要取i = s.length();

的值

只需将外部循环设为for(i=1; i<=s.length(); i++)

答案 3 :(得分:0)

制作ammendemends
for (i=1; i<s.length(); i++)

to 
for (i=1; i<=s.length(); i++)