java获取字符串最后一个字符

要获取字符串的最后一个字符,你可以使用以下方法之一:

方法1:使用 charAt() 方法

String str = "Hello World";
char lastChar = str.charAt(str.length() - 1);
System.out.println("最后一个字符是:" + lastChar);

方法2:使用 substring() 方法

String str = "Hello World";
String lastChar = str.substring(str.length() - 1);
System.out.println("最后一个字符是:" + lastChar);

在这两种方法中,我们使用 str.length() - 1 来获取字符串的最后一个字符的索引,然后使用 charAt() 方法 或将最后一个字符作为子字符串使用 substring() 方法。

请注意,以上方法假设字符串不为空,如果字符串可能为空,请在使用前进行非空检查以避免异常。

希望对你有帮助!如果你还有其他问题,请随时提问。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年12月21日
下一篇 2023年12月21日

相关推荐