21xrx.com
2025-03-26 14:11:19 Wednesday
文章检索 我的文章 写文章
C++:保留相同的字符
2023-07-05 00:20:35 深夜i     16     0
C++ 保留 相同字符

C++ 是一门常用的编程语言,经常被用于开发各种各样的应用程序。在很多情况下,需要比较字符串并保留相同的字符。这篇文章将介绍如何在 C++ 中实现这种操作。

首先,我们需要使用头文件“iostream”和“cstring”,前者用于输入输出,后者用于字符串处理。

#include <iostream>
#include <cstring>

接下来,我们需要定义两个字符串,分别表示要比较的两个字符串。在这里,我们将使用std::string类型来存储字符串。

std::string str1 = "hello";
std::string str2 = "world";

接下来,我们使用一个循环结构来比较两个字符串。在循环中,我们可以使用标准库函数“strlen”来获取字符串的长度。

for (int i = 0; i < strlen(str1.c_str()); ++i) {
 for (int j = 0; j < strlen(str2.c_str()); ++j) {
  if (str1[i] == str2[j]) {
   std::cout << str1[i];
   break;
  }
 }
}

在这里,我们使用了两个嵌套循环来比较两个字符串。在内部循环中,我们检查每个字符是否在第二个字符串中。如果相同,我们将该字符输出,并终止内部循环。

最后,我们还需要添加一行代码来输出结束符,以便正常结束程序。

std::cout << std::endl;

完整的代码如下所示:

#include <iostream>
#include <cstring>
int main() {
 std::string str1 = "hello";
 std::string str2 = "world";
 for (int i = 0; i < strlen(str1.c_str()); ++i) {
  for (int j = 0; j < strlen(str2.c_str()); ++j) {
   if (str1[i] == str2[j]) {
    std::cout << str1[i];
    break;
   }
  }
 }
 std::cout << std::endl;
 return 0;
}

在这个例子中,输出结果为“lo”。

总的来说,在 C++ 中保留相同的字符需要使用循环和字符串处理函数。通过上面的示例程序,您可以轻松地实现此操作,达到您的想法效果。

  
  

评论区