我想打印除最后一个、最后两个、最后三个之外的所有字母

我正在尝试打印这样的字符串:


cat

ca

c

但现在用我的代码,我只能得到


ttt

tt

t

代码


public static String bingo(String s) {

        int len = s.length();

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

            for(int k = 1; k <= s.length() - i+1; k++) {

                System.out.print(s.substring(len-5));

            }

            System.out.println();

        }

        return s;

    }


牛魔王的故事
浏览 180回答 4
4回答

拉丁的传说

您可以从长度迭代到 1 并打印每行中的子字符串:public static void bingo(String s) {&nbsp; &nbsp; for (int i = s.length(); i > 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s.substring(0, i));&nbsp; &nbsp; }}输出(对于猫)catcac

慕森王

你快明白了!这就是可以用 来完成的方法while loop。public static String bingo(String s) {&nbsp; &nbsp; int index = s.length();&nbsp; &nbsp; while (index != 0)&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s.substring(0, index--));&nbsp; &nbsp; return s;}这是如何完成的for looppublic static String bingo(String s) {&nbsp; &nbsp; for (int i = s.length(); i != 0; i--)&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s.substring(0, i));&nbsp; &nbsp; return s;}

慕容森

当然其他答案是正确的,但为什么不也以功能性的方式学习呢?// you can use the tails everywhere you need (require Java 9+)static Stream<String> tails(String xs) {&nbsp; &nbsp; return Stream.iterate(xs, x -> !x.isEmpty(), x -> x.substring(0, x.length() - 1));}// usage examplepublic static void main(String[] args) {&nbsp; &nbsp; tails("cat").forEach(System.out::println);}然而,这些参数是不言自明的(参见 javadoc iterate ):.iterate(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// iterate&nbsp; &nbsp; &nbsp; &nbsp; xs,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// using `xs` as seed&nbsp; &nbsp; &nbsp; &nbsp; x -> !x.isEmpty(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // as long as the condition is true&nbsp; &nbsp; &nbsp; &nbsp; x -> x.substring(0, x.length() - 1)&nbsp; &nbsp; &nbsp;// transform the current value);

largeQ

public static String bingo(String s) {&nbsp; &nbsp; int len = s.length();&nbsp; &nbsp; for(int i = 0; i <s.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s.substring(0,len-i));&nbsp; &nbsp; }&nbsp; &nbsp; return s;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java