gpt4 book ai didi

java - 从字符串中获取一个字符

转载 作者:太空狗 更新时间:2023-10-29 15:29:36 24 4
gpt4 key购买 nike

我有这个字符串:

String code="abc";

我想通过 substring 方法从这个字符串中提取“c”,但它不起作用:

String code="abc";
String getsmscode=code.substring(2,1);

这段代码返回一个错误

java.lang.StringIndexOutOfBoundsException: length=3; regionStart=2; regionLength=-1

但我不知道为什么?

最佳答案

您需要阅读 the documentation for substring - 第二个参数不是长度,它是结束索引(不包括)。

Parameters:
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.

如有疑问,请阅读文档...

另请注意,如果您只是想获取最后一个字符,则可以只使用单参数重载,它会返回从给定起点到字符串结尾的子字符串:

String lastCharacter = text.substring(text.length() - 1);

或者您可以将其作为单个字符获取:

char lastCharacter = text.charAt(text.length() - 1);

关于java - 从字符串中获取一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15389556/

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