string 找字串
时间: 2024-02-05 21:06:34 浏览: 23
好的,针对您的问题,可以使用 C++ 中的 string 类型和 find 函数来实现。具体代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "hello world";
string s2 = "world";
int pos = s1.find(s2);
if (pos != string::npos) {
cout << "找到了,位置是:" << pos << endl;
} else {
cout << "没找到" << endl;
}
return 0;
}
```
输出结果为:
```
找到了,位置是:6
```
其中,find 函数返回的是子串在原字符串中的位置,如果找不到则返回 string::npos。
相关问题
判断string中包含字串
可以使用string.find函数来判断string中是否包含字串,该函数返回字串在string中的起始位置和结束位置,如果不存在则返回nil。例如,判断字符串str中是否包含字串substr,可以使用以下代码:
if string.find(str, substr) then
print("字符串中包含字串")
else
print("字符串中不包含字串")
end
std::string 字串转整形
可以使用`std::stoi`函数将`std::string`类型的字符串转换为整数。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int num = std::stoi(str);
std::cout << "转换后的整数为:" << num << std::endl;
return 0;
}
```
输出结果为:
```
转换后的整数为:12345
```