I have written code to find a duplicate char from a string. Can the code be improved?
Input:
Hello World
output :
l = 3 its a dup
o = 2 its a dup
My approach is
step 1: sort the string
step 2: remove all the whitespace
step 3: copy std::string
to char []
and loop through the array until different char and count on every dup char if count is more than one its duplicate.
#include<iostream>
#include<algorithm>
#include<set>
#include<string>
#include<string.h>
#include<unistd.h>
void dupcheck(std::string usr)
{
int count =1;
char temp[1024]={0};
strncpy(temp,usr.c_str(),sizeof(temp));
for(int i=0;temp[i];++i)
{
for(int j=i+1;temp[j]==temp[i];++j)
{
if(temp[i]==temp[j])
count++;
i=j;
}
if(count>=2)
{
std::cout<<"dup char ="<<temp[i]<<" "<<count<<std::endl;
count =1;
}
}
}
int main()
{
std::string userInput;
std::getline(std::cin,userInput);
userInput.erase(std::remove(userInput.begin(), userInput.end(),' '), userInput.end());
std::sort(userInput.begin(),userInput.end());
std::cout<<userInput<<std::endl;
if(!userInput.empty())
dupcheck(userInput);
}
Please help me to improve the code if possible.