public char charAt(int index)方法 String类的public char charAt(int index)方法可以得到当前字符串index位置上的一个字符。编写程序使用该方法得到一个字符串中的第一个和最后一个字符。 例如测试的字符串为:ABCDabcd 输出:A d
时间: 2024-03-01 21:56:04 浏览: 33
好的,下面是一个Java程序示例,可以实现您的需求:
```
public class Main {
public static void main(String[] args) {
String str = "ABCDabcd";
char firstChar = str.charAt(0);
char lastChar = str.charAt(str.length() - 1);
System.out.println("第一个字符是:" + firstChar);
System.out.println("最后一个字符是:" + lastChar);
}
}
```
在这个示例中,首先定义了一个字符串变量str,然后使用charAt方法获取了字符串的第一个字符和最后一个字符,分别赋值给了firstChar和lastChar变量。最后使用System.out.println方法打印输出结果。
相关问题
public char charAt(int index)方法 String类的public char charAt(int index)方法可以得到当前字符串index位置上的一个字符。编写程序使用该方法得到一个字符串中的第一个和最后一个字符。
好的,这个问题很简单,以下是获取字符串中第一个和最后一个字符的示例代码:
```java
public static void main(String[] args) {
String str = "Hello World!";
char firstChar = str.charAt(0);
char lastChar = str.charAt(str.length() - 1);
System.out.println("第一个字符是:" + firstChar);
System.out.println("最后一个字符是:" + lastChar);
}
```
运行结果:
```
第一个字符是:H
最后一个字符是:!
```
以上代码使用了`charAt()`方法来获取字符串中的第一个和最后一个字符,其中第一个字符的位置为0,最后一个字符的位置为字符串长度减1。注意,如果字符串为空或者索引越界,`charAt()`方法会抛出`StringIndexOutOfBoundsException`异常,需要进行异常处理。
String类的 public char charAt(int index)方法可以得到当前字符串Index位置上的一个字符。编写程序,使用该方法得到一个字符串中的第一个和最后一个字符。
可以使用如下代码来获取一个字符串的第一个和最后一个字符:
```java
String str = "Hello, world!";
char firstChar = str.charAt(0);
char lastChar = str.charAt(str.length()-1);
System.out.println("第一个字符为:" + firstChar + ",最后一个字符为:" + lastChar);
```
输出结果为:
```
第一个字符为:H,最后一个字符为:!
```
其中,`charAt()`方法用于获取指定索引位置上的字符,索引从0开始,因此第一个字符的索引为0,最后一个字符的索引为字符串长度-1。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)