java 中String获取最后一个字符
时间: 2023-05-29 21:05:32 浏览: 147
可以使用 charAt() 方法获取最后一个字符。
示例代码:
```java
String str = "Hello World!";
char lastChar = str.charAt(str.length() - 1);
System.out.println("最后一个字符是:" + lastChar);
```
输出结果:
```
最后一个字符是:!
```
相关问题
Java中如何获取最后一个字符的下标
可以使用字符串的`length()`方法获取字符串的长度,然后将长度减1即可得到最后一个字符的下标。
示例代码如下:
```java
String str = "Hello World";
int lastIndex = str.length() - 1; // 获取最后一个字符的下标
char lastChar = str.charAt(lastIndex); // 获取最后一个字符
System.out.println("最后一个字符的下标为:" + lastIndex);
System.out.println("最后一个字符为:" + lastChar);
```
Java String字符串去除最后一个空格
可以使用以下代码来去除Java String字符串中的最后一个空格:
```java
String str = "This is a sample string ";
int lastIndex = str.lastIndexOf(' ');
String result = str.substring(0, lastIndex);
```
这里使用了 `lastIndexOf()` 方法来查找最后一个空格的位置,并使用 `substring()` 方法从字符串开头截取到该位置,获取去除最后一个空格后的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)