使用String类的public char charAt(int index)方法可以得到当前字符串index位置上的一个字符。编写程序使用该方法得到一个字符串中的第一个和最后一个字符。
时间: 2024-04-29 17:22:37 浏览: 18
可以这样编写程序:
```java
public class CharAtDemo {
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("The first character is " + firstChar);
System.out.println("The last character is " + lastChar);
}
}
```
输出结果为:
```
The first character is H
The last character is !
```
相关问题
使用javapublic char charAt(int index)方法 String类的public char charAt(int index)方法可以得到当前字符串index位置上的一个字符。编写程序使用该方法得到一个字符串中的第一个和最后一个字符。
好的,以下是使用Java编写的程序,可以得到一个字符串中的第一个和最后一个字符:
```java
public class FirstAndLastChar {
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("The first character of the string is: " + firstChar);
System.out.println("The last character of the string is: " + lastChar);
}
}
```
在这个程序中,我们首先定义了一个字符串 `str`,然后使用 `charAt()` 方法得到了字符串的第一个和最后一个字符。其中,第一个字符的位置是0,最后一个字符的位置是字符串长度减1(因为字符串下标从0开始)。
最后,我们使用 `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`异常,需要进行异常处理。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)