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

时间:2018-11-26 20:58:53

标签: java

我是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.

2 个答案:

答案 0 :(得分:1)

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

String vacantion = "Vacantion";

int number = 1;

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

    number++;
}

答案 1 :(得分:-1)

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

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

例如:

Assembly reference changes detected. Restarting host...
Environment shutdown has been triggered. Stopping host and signaling shutdown.
completed successfully
Function completed (Success, Id=d5042f25-18d9-489a-81fe-05ae07607012, Duration=10921ms)
Executed 'AzureBillFunc' (Succeeded, Id=d5042f25-18d9-489a-81fe-05ae07607012)
The host started (12276ms)
A ScriptHost error has occurred
Microsoft.Azure.WebJobs.Host: Cannot access a disposed of object. Stopping Host

希望这会有所帮助!