#include<iostream>
#include<cstdlib>
#include<cctype>
#include <iomanip>
#include <cstring>
//----------------------
using std :: cin;
using std :: cout;
using std :: endl;
using std::setw ;
//-------------------
const int MAX_STR_LEN=100;
//-----------------------
int main()
{
char str1 [MAX_STR_LEN];
char str2 [MAX_STR_LEN];
int i;
cin >> setw(MAX_STR_LEN)>>str1;
cin >> setw(MAX_STR_LEN)>>str2;
if (strcmp(str1, str2)!=0)
{
for (int i=0; i < strlen(str1); i++)
{
for (int j=0; j < strlen(str2); j++)
{
if (str1[i]==str2[j]) // we want to check whats common first
// and then cout whats left (not common)
{
cout << str2[j];
}
}
}
return EXIT_SUCCESS;
}
如果我正在寻找常见字符,这非常有效。
我试过这个循环:if (str1[i]!=str2[j])
但因为它在 for loops
中所以它给了我 i 之间的区别
和所有字符串 j
。例如,如果 str1=abc
和 str2=abcd
答案应该是 d
最佳答案
如果您不能自己更改字符串,那么您可以使用带有 std::set
容器的方法。例如
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
int main()
{
std::string s1( "abd" );
std::string s2( "ace" );
std::set<char> set1( s1.begin(), s1.end() );
std::set<char> set2( s2.begin(), s2.end() );
std::set_symmetric_difference( set1.begin(), set1.end(), set2.begin(), set2.end(),
std::ostream_iterator<char>( std::cout ) );
std::cout << std::endl;
}
输出是
bcde
至少程序为字符串 abc
和 abcd
给出了预期的结果 d
。:)
否则,您可以对字符串进行排序并应用相同的标准算法 std::set_symmetric_difference
。
关于c++ - 在 C++ 中读取所有字符的 2 个字符串之间输出不同字符(不是公共(public)字符)的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34827155/