string类中定位指定字符下标
时间: 2024-02-12 07:07:15 浏览: 29
在C++中,`string`类提供了多种方法来定位指定字符的下标,例如:
1. `find(char c)`函数:返回字符`c`在字符串中第一次出现的下标,如果未找到则返回`string::npos`。
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
size_t pos = str.find('o');
if (pos != string::npos) {
cout << "The index of the first 'o' is: " << pos << endl;
} else {
cout << "The character 'o' is not found in the string." << endl;
}
return 0;
}
```
输出:
```
The index of the first 'o' is: 4
```
2. `rfind(char c)`函数:返回字符`c`在字符串中最后一次出现的下标,如果未找到则返回`string::npos`。
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
size_t pos = str.rfind('o');
if (pos != string::npos) {
cout << "The index of the last 'o' is: " << pos << endl;
} else {
cout << "The character 'o' is not found in the string." << endl;
}
return 0;
}
```
输出:
```
The index of the last 'o' is: 8
```
3. `find_first_of(char c)`函数:返回字符串中任意一个字符在字符串中第一次出现的下标,如果未找到则返回`string::npos`。
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
size_t pos = str.find_first_of("lo");
if (pos != string::npos) {
cout << "The index of the first 'l' or 'o' is: " << pos << endl;
} else {
cout << "The characters 'l' and 'o' are not found in the string." << endl;
}
return 0;
}
```
输出:
```
The index of the first 'l' or 'o' is: 2
```
4. `find_last_of(char c)`函数:返回字符串中任意一个字符在字符串中最后一次出现的下标,如果未找到则返回`string::npos`。
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
size_t pos = str.find_last_of("lo");
if (pos != string::npos) {
cout << "The index of the last 'l' or 'o' is: " << pos << endl;
} else {
cout << "The characters 'l' and 'o' are not found in the string." << endl;
}
return 0;
}
```
输出:
```
The index of the last 'l' or 'o' is: 10
```