c++比较字符串是不是子串
时间: 2024-01-02 22:05:10 浏览: 30
可以使用C++中的string类的find函数来判断一个字符串是否为另一个字符串的子串。具体实现如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello world";
string str2 = "world";
if (str1.find(str2) != string::npos) {
cout << str2 << " is a substring of " << str1 << endl;
} else {
cout << str2 << " is not a substring of " << str1 << endl;
}
return 0;
}
```
输出结果为:
```
world is a substring of hello world
```
相关问题
c++ 字符串查找子串
以下是C++中字符串查找子串的例子:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "abcdefghigklmn";
string b = "def";
string c = "123";
string::size_type idx;
idx = a.find(b); // 在a中查找b
if (idx == string::npos) // 不存在
cout << "not found\n";
else // 存在
cout << "found\n";
return 0;
}
```
该程序中,使用了string类的find()函数来查找子串。如果子串存在,则返回子串在原字符串中的起始位置;如果不存在,则返回string::npos。在该程序中,我们定义了三个字符串a、b、c,其中a为原字符串,b为要查找的子串,c为一个不存在于a中的字符串。程序首先在a中查找b,如果存在,则输出“found”;如果不存在,则输出“not found”。
C++字符串包含子串
要判断C语言字符串是否包含子串,可以使用库函数strstr()。这个函数在一个字符串中查找另一个字符串的第一次出现,并返回一个指向该位置的指针。如果找不到,它将返回NULL。
例如,如果我们有一个原始字符串为char *类型的字符串jsonData和一个子串为string类型的字符串str,我们可以使用以下代码来判断jsonData是否包含str:
```c
const char *show;
show = strstr(jsonData, str.c_str());
if (show != NULL) {
// jsonData包含子串str
} else {
// jsonData不包含子串str
}
```
另外,如果你想将C字符串写入txt文件,可以使用C++的fstream库来实现。首先,你需要包含<iostream>、<iomanip>和<fstream>头文件。然后,你可以使用ofstream类创建一个输出文件流对象outfile,并使用open()函数打开你想要写入的txt文件。如果你想追加写入文件而不是覆盖原有内容,可以在open()函数中使用ios::app参数。最后,你可以使用<<操作符将字符串写入文件,并使用endl来进行换行。写入完成后,记得关闭文件流outfile。以下是一个示例代码:
```c
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
char *jsonData = "abcdefg";
ofstream outfile;
outfile.open("G:\\jsonData.txt", ios::app);
if (outfile.is_open()) {
outfile << jsonData << endl;
} else {
cout << "不能打开文件!" << endl;
}
outfile.close();
return 0;
}
```<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [C++判断字符串里是否含有子字符串](https://blog.csdn.net/weixin_44353958/article/details/120965488)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [C++判断字符串中是否含有某个子字符串](https://blog.csdn.net/hnyzwtf/article/details/52038667)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]