对于任意输入的两个字符串 请编写程序输出其中的公共字符
时间: 2024-05-09 20:17:08 浏览: 20
好的,现在开始回答你的问题。以下是一个用 Python 编写的程序,可以输出任意输入的两个字符串中的公共字符:
```python
str1 = input("请输入第一个字符串:")
str2 = input("请输入第二个字符串:")
common_chars = ""
for char in str1:
if char in str2 and char not in common_chars:
common_chars += char
if common_chars:
print("这两个字符串的公共字符为:{}".format(common_chars))
else:
print("这两个字符串没有公共字符。")
```
这个程序的思路是,先接收用户输入的两个字符串,并定义一个空字符串 common_chars 用来存储公共字符。然后遍历第一个字符串的所有字符,如果这个字符同时存在于第二个字符串中,且还没有被记录在公共字符中,那么就把它添加到 common_chars 中。最后,输出 common_chars 即可。
希望这个程序能够解决你的问题,如果你还有其他问题,可以继续问我哦。
相关问题
输入两个任意的字符串,编写程序实现两个字符串的链接不能使用strcat 函数
好的,我可以帮你编写这样的程序。以下是一个示例代码,可以实现两个字符串的链接操作:
```c
#include <stdio.h>
int main()
{
char str1[100], str2[100];
int i = 0, j = 0;
printf("请输入第一个字符串:\n");
gets(str1);
printf("请输入第二个字符串:\n");
gets(str2);
// 找到 str1 的末尾
while (str1[i] != '\0') {
i++;
}
// 将 str2 添加到 str1 后面
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
// 在新字符串末尾添加空字符
str1[i] = '\0';
printf("链接后的字符串为:%s\n", str1);
return 0;
}
```
在这个程序中,我们首先使用 `gets` 函数分别读取两个字符串。然后,我们使用两个 while 循环来将第二个字符串添加到第一个字符串的末尾。最后,我们在新字符串的末尾添加了一个空字符 '\0',以表示字符串的结尾。
需要注意的是,这个程序中并没有使用 `strcat` 函数,而是使用了自己编写的代码实现了字符串的链接操作。
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++ 编译器进行编译运行。
请注意,我只提供了一个简单的实现,可能并不是最优的解决方案。在实际应用中,你可能需要考虑更多的边界情况和优化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)