cpp查找字符串中指定字符串中的位置
时间: 2024-04-12 10:26:38 浏览: 17
在C++中,你可以使用`std::string`的`find`函数来查找一个字符串中指定子字符串的位置。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World!";
std::string subStr = "World";
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`在`str`中的位置。如果找到子字符串,`find`函数会返回子字符串在主字符串中的起始位置;如果未找到,`find`函数会返回`std::string::npos`。
相关问题
cpp查找字符串中指定字符串第一次出現的位置
在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`。
c++将字符串中的指定字符串取出
您可以使用C++的字符串处理函数来取出指定的子字符串。以下是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, C++ programming!";
std::string subStr = "C++";
size_t found = str.find(subStr);
if (found != std::string::npos) {
str.erase(found, subStr.length());
std::cout << "Modified string: " << str << std::endl;
} else {
std::cout << "Substring not found!" << std::endl;
}
return 0;
}
```
在上面的代码中,我们首先定义了一个字符串 `str`,其中包含了要处理的原始字符串。然后,我们定义了一个 `subStr` 字符串,它表示要取出的子字符串。我们使用 `find` 函数来查找子字符串在原始字符串中的位置。如果找到了子字符串,则使用 `erase` 函数将其从原始字符串中移除。最后,我们输出修改后的字符串。
请注意,上述代码只会删除第一次出现的子字符串。如果要删除所有出现的子字符串,可以使用循环来多次执行查找和删除操作。
希望这可以帮助到您!