请问怎么找出string中只出现过一次的字符?例如"abcdef abcd"中需要得到ef。新手刚接触c++。。。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string temp = "";
cout << "请输入字符串:";
cin >> temp;
string str = ""; //存放只出现一次的字符
string str1 = ""; //存放重复的字符
for (int i = 0; i < temp.length(); i++)
{
string tempSub = temp.substr(i, 1);
int b = temp.rfind(tempSub); //从后向前查找字符出现的位置
if (i == b && str1.find(tempSub) == -1) //如果b和遍历查找的位置一致,且str1 里没有该字符,说明只出现一次
str +=temp.substr(i, 1);
else if (str1.find(tempSub) == -1)
str1 += temp.substr(i, 1);;
}
cout << "只出现一次的字符:" << str << endl;
cout << "重复出现的字符的字符:" << str1 << endl;
system("pause");
return 0;
}
定义一个数组大小为128,数组下标对应一个ascii字符的值,循环字符串中的字符,出现一次就加i++。最后统计次数为1的字符就可以了。
望采纳,谢谢!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abc abcde abcdefgh";
string sub = "abc";
int index = 0;
int count = 0;
while ((index = s.find(sub, index)) < s.length())
{
count++;
index++;
}
cout << count << endl;
return 0;
}
从abcdefabcd中截取i个长度的字符串,然后看看改字符串的出现次数,i的长度是从2到逐渐递增。
遍历i长度字符串的每一种可能。
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632