给定一个字符串,找出该字符串中第一个只出现一次的字符。
char FirstNonRepeated(string& str)
{
//find the first char in str that appears only once
//找到str中第一个只出现一次的字符
//假设只有ascii字符
short chars[256];
memset(chars, 0, 256);
for(int i = 0; i < str.size(); ++i)
{
if(chars[str[i]] <= 1)
++chars[str[i]];
}
for(int i = 0; i < str.size(); ++i)
if(1 == chars[str[i]])
return str[i];
return 0;
}
int main()
{
cout << FirstNonRepeated(string("total")) << endl;
cout << FirstNonRepeated(string("teeter")) << endl;
cout << FirstNonRepeated(string("teeterr")) << endl;
cout << FirstNonRepeated(string("")) << endl;
cout << FirstNonRepeated(string("x")) << endl;
cout << FirstNonRepeated(string("xx")) << endl;
return 1;
}
字符串中第一个只出现一次的字符
最新推荐文章于 2021-11-09 16:32:28 发布