string类charAT()
时间: 2023-08-07 11:09:39 浏览: 45
string类的charAT()函数用于返回字符串中指定位置的字符。
函数原型:
```
char charAT(int index) const;
```
参数:
- index:要返回的字符的位置,从0开始计数。
返回值:
- 返回指定位置的字符。
示例:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
char ch1 = str.at(1); // 获取第2个字符
char ch2 = str.at(6); // 获取第7个字符
cout << ch1 << endl; // 输出 'e'
cout << ch2 << endl; // 输出 'w'
return 0;
}
```
注意:
- 如果指定的位置超出了字符串的长度,会抛出一个 `out_of_range` 异常。
- 可以使用下标运算符 [] 来获取指定位置的字符,例如:`char ch = str[0];`。但是,下标运算符不会检查指定位置是否超出范围,如果超出范围会导致程序崩溃。因此,建议使用 at() 函数来获取字符。
相关问题
String类charAt()
String类的charAt()方法是用来获取字符串中指定位置的字符。它的语法如下:
```java
char charAt(int index)
```
其中,index表示要获取的字符在字符串中的位置,位置从0开始。
例如,下面的代码获取了字符串"hello"中第2个字符(即字符'l'):
```java
String str = "hello";
char c = str.charAt(2);
System.out.println(c); // 输出'l'
```
需要注意的是,如果指定的位置超出了字符串的范围,charAt()方法会抛出IndexOutOfBoundsException异常。
String.charAt
String.charAt() 是 Java 中 String 类的一个方法,它用于返回字符串中指定索引位置的字符。该方法的语法如下:
```java
public char charAt(int index)
```
其中,index 表示要返回的字符的索引位置。索引位置从 0 开始,即第一个字符的索引位置为 0,第二个字符的索引位置为 1,以此类推。
例如,下面的代码演示了如何使用 charAt() 方法获取字符串中第一个字符和第二个字符:
```java
String str = "Hello World";
char firstChar = str.charAt(0); // 获取第一个字符
char secondChar = str.charAt(1); // 获取第二个字符
System.out.println("第一个字符是:" + firstChar);
System.out.println("第二个字符是:" + secondChar);
```
运行结果为:
```
第一个字符是:H
第二个字符是:e
```