C++分两行输入两个字符串(最长30个字符),在第一个字符串中查找第二个字符串是否存在,存在输出“yes”,不存在则输出“no”。
时间: 2024-02-16 18:00:00 浏览: 24
好的,以下是 C++ 的代码实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[31], str2[31];
cin.getline(str1, 31);
cin.getline(str2, 31);
if (strstr(str1, str2) != NULL) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
return 0;
}
```
首先定义两个字符数组 `str1` 和 `str2`,并使用 `cin.getline()` 分别输入两个字符串,其中 `31` 表示最多输入 30 个字符,最后一个字符默认为 `\0`。
然后使用 `strstr()` 函数在 `str1` 中查找 `str2`,如果返回值不为 `NULL`,说明 `str2` 存在于 `str1` 中,输出 `yes`,否则输出 `no`。
相关问题
C++输入两个字符串将两个字符串合并成一个字符串
以下是将两个字符串合并成一个字符串的C++代码示例:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[50], str2[50];
cout << "请输入第一个字符串:";
cin >> str1;
cout << "请输入第二个字符串:";
cin >> str2;
strcat(str1, str2); // 将str2拼接到str1后面
cout << "合并后的字符串为:" << str1 << endl;
return 0;
}
```
C++输入任意两个字符串S1,S2,输出两个字符串的最长公共前缀,如果没有输出空字符串
好的,以下是用 C++ 编写的代码来实现你的需求:
```cpp
#include <iostream>
#include <string>
using namespace std;
string longestCommonPrefix(string s1, string s2) {
string result = "";
int i = 0;
while (i < s1.length() && i < s2.length() && s1[i] == s2[i]) {
result += s1[i];
i++;
}
return result;
}
int main() {
string s1, s2;
cout << "请输入字符串S1: ";
cin >> s1;
cout << "请输入字符串S2: ";
cin >> s2;
string commonPrefix = longestCommonPrefix(s1, s2);
if (commonPrefix.empty()) {
cout << "两个字符串没有最长公共前缀。" << endl;
} else {
cout << "最长公共前缀为: " << commonPrefix << endl;
}
return 0;
}
```
你可以将以上代码保存为 `.cpp` 文件,然后使用 C++ 编译器进行编译运行。
请注意,我只提供了一个简单的实现,可能并不是最优的解决方案。在实际应用中,你可能需要考虑更多的边界情况和优化。