C++ 程序在一个给定的两个字符串中找出不同寻常的字符
在本文中,我们将讨论一个程序,以找出比较两个给定字符串时不同的字符。
众所周知,字符串不过是字符的数组。因此,为了比较,我们将遍历一个字符串的字符,并同时检查该元素是否存在于另一个字符串中。
如果我们让第一个字符串是 A,第二个字符串是 B,那么它将给我们A - B。同样,我们可以计算B - A。
将这两个结果组合起来,我们会得到
( A - B ) ∪ ( B - A )
即,两个字符串中不相同的元素。
示例
#include <iostream>
using namespace std;
int main() {
int len1 = 5, len2 = 4;
char str1[len1] = "afbde", str2[len2] = "wabq";
cout << "Uncommon Elements :" <<endl;
//loop to calculate str1- str2
for(int i = 0; i < len1; i++) {
for(int j = 0; j < len2; j++) {
if(str1[i] == str2[j])
break;
//when the end of string is reached
else if(j == len2-1) {
cout << str1[i] << endl;
break;
}
}
}
//loop to calculate str2- str1
for(int i = 0; i < len2; i++) {
for(int j = 0; j < len1; j++) {
if(str2[i] == str1[j])
break;
else if(j == len1-1) {
cout << str2[i] << endl;
break;
}
}
}
return 0;
}输出
Uncommon Elements : f d e w q
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP