如何获取字符串的最后一个字符,然后是最后两个字符,依此类推



我是java初学者,我需要帮助,我想打印字符串的最后一个字符,然后打印最后两个。。等等。

非常感谢您的时间和帮助。(我不需要视频教程建议等(

String vacantion = "Vacantion";
int number = 1;
for (int i = 0; i < vacantion.length(); i++) 
{
System.out.println(vacantion.charAt(vacantion.length() - number));
number++;
}
// The output should look like this //
// n,
// on,
// ion,
// tion,
// so on.

您需要用子字符串方法替换charAt方法:

String vacantion = "Vacantion";
int number = 1;
for (int i = 0; i < vacantion.length(); i++)
{
System.out.println(vacantion.substring(vacantion.length() - number));
number++;
}

要获取任何字符串的字符,您可以使用string.substring(firstIndex,lastIndex(或string.charAt(index(.

substring(firstIndex,lastIndex(将为您提供介于firstIndex和lastIndex之间的字母(包括first,不包括last(,而charAt(index(将在您的String中返回该索引处的字符(请注意,charAt(将始终且仅返回1个字符(。

例如:

String sample = "Hello World";
// substring() examples
System.out.println(sample.substring(0,5); // This would give you an output of "Hello"
System.out.println(sample.substring(6, sample.length()); // This would give you "World"
// charAt() examples
System.out.println(sample.charAt(4)); // This would return 'o'
System.out.println(sample.charAt(str.length() - 1); // This would give you 'd'

希望这能有所帮助!

最新更新