gpt4 book ai didi

java - 如何按递减顺序循环字符串?

转载 作者:行者123 更新时间:2023-12-02 10:06:26 26 4
gpt4 key购买 nike

编写一个程序,获取用户输入的字符串,然后输出第一个字符,然后是前两个,然后是前三个,依此类推,直到打印整个单词。向下打印一个字母后,将相反的字母打印到整个单词。

我已经完成了第一部分。

   Scanner word = new Scanner(System.in);
System.out.println("Enter a word.");
String thing = word.next();
String rest = "";
for(int i=0;i< thing.length();i++){
String w = thing.substring(i,i+1);
rest += w;
System.out.println(rest);
}

这就是它应该的样子。

C
Co
Com
Comp
Compu
Comput
Compute
Computer
Computer
Compute
Comput
Compu
Comp
Com
Co
C

最佳答案

Java 中的字符串从 0 开始索引,因此最后一个字符的索引为 length-1

要从最后一个字符向下迭代到第一个字符,for 循环将为 for(int i = thing.length () - 1; i >= 0; i--)

或者,考虑到您已经获得了应该反向打印的字符串,递归将是一个更简单的解决方案。

static void f (String str, int n) {
if (n > str.length ()) return;
String temp = str.substring (0, n); // obtain the string
System.out.println (temp); // print
f (str, n + 1); // go to next substring
System.out.println (temp); // print after returning from the last obtainable substring
}

现在可以通过 f(thing, n); 调用该函数

关于java - 如何按递减顺序循环字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com