c++ 找到字元串中第一個出現重複的字元和第一個不重複的字元
我們可以使用map容器來記錄字元串中字元和它對應的次數
map容器第一個參數為鍵(key),第二個參數為值(value)
定義map<char,int>,char:表示字元 int:字元出現的次數
話不多說,直接上代碼啦!
①找到字元串中第一個出現重複的字元
(1)第一種方法,使用map
#include <iostream>
#include <map>
#include <string>
using namespace std;
void firstrepeatchar(string s)
{
int len = s.length(); //字元串長度
map<char, int> str; //char:字元 int:字元出現的次數,map不初始化時,value為int型時,預設為0
for (int i = 0; i < len; i++)
{
str[s[i]]++; //字元出現的次數,s[i]為鍵,str[s[i]]++表示s[i]出現的次數
}
for (int i = 0; i < len; i++)
{
if (str[s[i]] > 1)
{
cout << s[i] << endl;
break; //找到一個重複字元,跳出循環。
}
}
}
int main()
{
string str;
while (getline(cin,str))
{
firstrepeatchar(str);
}
system("pause");
return 0;
}
(2)第2種方法,不使用map
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
string str;
int len; //字元串長度
int index; //索引
while (getline(cin,str))
{
len = str.length();
for (int i = 0; i < len; i++)
{
index = str.find(str[i], i + 1); //與str[i]相等的第一個字元的索引
if (index != str.npos) //表示索引存在
{
cout << str[i] << endl;
//i = len;
break;
}
}
}
system("pause");
return 0;
}
測試結果
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2YfNWawNyZuBnL1QDNxATM0AjM0EDOwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
②找到字元串中第一個出現不重複的字元
(1)第一種方法,使用map
#include <iostream>
#include <string>
#include <map>
using namespace std;
void findfirstnorepeat(string s)
{
int len = s.length();
map<char, int> str; //char:字元 int:字元出現的次數
int count = 0;
for (int i = 0; i < len; i++)
{
str[s[i]]++; //字元出現的次數
}
for (int i = 0; i < len; i++)
{
if (str[s[i]] == 1)
{
cout << s[i] << endl;
break;
}
}
}
int main()
{
string str;
while (getline(cin,str))
{
findfirstnorepeat(str);
}
system("pause");
return 0;
}
(2)第2種方法,不使用map
#include <iostream>
#include <string>
#include <map>
using namespace std;
void findfirstnorepeat(string s)
{
int a[128] = { 0 }; //初始化為0
int len = s.length(); //字元串長度
for (int i = 0; i < len; i++)
{
a[s[i]]++; //字元出現次數
}
for (int i = 0; i < len; i++)
{
if (a[s[i]] == 1)
{
cout << s[i] << endl;
break;
}
}
}
int main()
{
string str;
while (getline(cin,str))
{
findfirstnorepeat(str);
}
system("pause");
return 0;
}
測試結果
希望能幫到大家!!!😊