Reputation:
This is my code to print duplicate character in C++.
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
char string[80];
cin.getline(string,80);
for(int i=0;i<strlen(string);i++){
for(int j=i+1;j<strlen(string);j++){
if(string[i]==string[j]){
if(string[i] != ' ')
cout<<string[i]<< " ";
break;
}
}
}
return 0;
}
If the input is ravuri
, the output is r
If the input is malayalam
, the output is:
malayalam
m
a
l
a
a
The code is supposed to print m a l
. Why is it printing the same character multiple times instead of one time?
Upvotes: 0
Views: 273
Reputation: 15267
This piece of code is a one to one copy from a blog post "codespeedy.com".
Here it is:
How to print duplicate characters from a given string in C++
The answer to your question is given in the section Explanation:
Print the duplicate values each time any duplicate character is detected
So, this piece of code will print the duplicate values each time any duplicate character is detected.
This has been posted by user Yash Shakya. Unfortunately, and I am really very sory to say, the code has nothing to do with C++. The quality is low:
using namespace std;
string
as a variable nameThis program is pure C-COde with the usage of std::cout
"CodeSpeedy" is advertising with
Hire us for your software development, mobile app development and web development project.
They should be really careful, what is posted on their page . . .
Upvotes: 0
Reputation: 163
Analyzing your codes, your code check the only characters rear to any character.
That is, if you input malayalam
and i is 1 while for
operates, your code check if a
exists in layalam
.
Then, there are three a
s. However, your code doesn't print these a
s all.
Your code will print a
only once.
Therefore,
i=0 → string[0]='m' → m
i=1 → string[1]='a' → a a a
i=2 → string[2]='l' → l
i=3 → string[3]='a' → a a
i=4 → string[4]='y' →
i=5 → string[5]='a' → a
i=6 → string[6]='l' →
i=7 → string[7]='a' →
i=8 → string[8]='m' →
By this progress, your code will print the characters along your input.
Upvotes: 2