返回某个字符在string中的下标
时间: 2024-03-01 09:55:33 浏览: 51
要返回某个字符在`std::string`中的下标,可以使用`std::string`的`find`函数。这个函数可以在字符串中查找指定的子串,并返回该子串在字符串中的起始位置。
由于字符也可以看作是长度为1的子串,因此可以将要查找的字符转换成一个长度为1的字符串,然后调用`find`函数进行查找。若查找成功,则返回匹配子串在字符串中的起始位置;否则返回`std::string::npos`。
以下是一个示例代码,用于返回字符在`std::string`中的下标:
```C++
#include <iostream>
#include <string>
int get_char_index(const std::string& str, char c) {
std::string s(1, c); // 将字符转换成长度为1的字符串
size_t index = str.find(s); // 在字符串中查找该字符
if (index != std::string::npos) {
return static_cast<int>(index); // 找到了返回下标
} else {
return -1; // 没有找到返回-1
}
}
int main() {
std::string str = "Hello, World!";
char c = 'W';
int index = get_char_index(str, c);
if (index != -1) {
std::cout << "The index of character " << c << " in string is: " << index << std::endl;
} else {
std::cout << "The character " << c << " is not found in string." << std::endl;
}
return 0;
}
```
在这个示例代码中,我们定义了一个函数`get_char_index`,用于返回字符在`std::string`中的下标。首先,将要查找的字符转换成一个长度为1的字符串`s`,然后调用`find`函数在字符串中查找该字符串。若找到了,返回匹配子串在字符串中的下标;否则返回-1。最后,在主函数中调用`get_char_index`函数,并输出结果。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)