cpp查找字符串中指定字符串第一次出現的位置
时间: 2023-10-04 22:11:32 浏览: 95
在C++中,你可以使用`std::string`的`find`函数来查找字符串中指定子字符串第一次出现的位置。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World! Hello!";
std::string subStr = "Hello";
size_t found = str.find(subStr);
if (found != std::string::npos) {
std::cout << "第一次出现的位置: " << found << std::endl;
} else {
std::cout << "未找到子字符串" << std::endl;
}
return 0;
}
```
在上面的示例中,我们定义了一个字符串`str`,然后使用`find`函数来查找子字符串`subStr`第一次出现的位置。如果找到子字符串,`find`函数会返回子字符串在主字符串中的起始位置;如果未找到,`find`函数会返回`std::string::npos`。
相关问题
qt中字符串获取字符第一次出现的位置
在Qt中,可以使用QString::indexOf函数来获取字符串中第一次出现某个字符的位置。
函数原型如下:
```
int QString::indexOf(QChar ch, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
```
其中,ch为要查找的字符,from为查找的起始位置(默认为0,表示从字符串的开头开始查找),cs为查找时是否区分大小写(默认为Qt::CaseSensitive,表示区分大小写)。
示例代码如下:
```cpp
QString str = "Hello, world!";
QChar ch = 'o';
int index = str.indexOf(ch);
qDebug() << "Index of " << ch << ": " << index; // 输出:Index of o: 4
```
上述代码中,我们首先定义了一个字符串str和要查找的字符ch,然后调用indexOf函数来获取ch在str中第一次出现的位置,并将结果存储在变量index中。最后,我们使用qDebug函数输出结果。
上述代码输出的结果是4,表示字符'o'在字符串中第一次出现的位置是4(从0开始计数)。
统计字符串中字符串出现的次数cpp
您好,可以为您解答问题。统计字符串中字符串出现的次数可以通过遍历字符串,依次搜索子字符串,再尝试匹配的方式来实现。以下是一段 C++ 代码示例:
```cpp
// 统计字符串中字符串出现的次数
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "This is a test sentence. It contains the word test twice.";
string searchStr = "test";
int count = 0;
size_t pos = str.find(searchStr); // 查找子字符串第一次出现的位置
while (pos != string::npos) // 如果存在子字符串
{
count++; // 子字符串出现次数+1
pos = str.find(searchStr, pos + 1); // 继续查找下一次子字符串出现的位置
}
cout << "The string \"" << searchStr << "\" appears " << count << " times in the string." << endl;
return 0;
}
```
希望能够帮到您,谢谢!