string count without counting spaces and character which is repeated

I made a code which can count length of a string in characters without space, But I want add an feature which count any repeated char as one, so Please help me out to do so, my code is written below:

#include<iostream>
#include<string>
using namespace std;

int count(string s){
char chr;
int num = 0;
for(int i = 0; i<(s.length()); i++){
chr = s[i];
num++;
if(chr == ' '){
num -= 1;
}
else if (char == )

}
return num;
}

int main()
{
string str;
cout << "\nIt is simple counting string program\n\n"<< "\tEnter a string: ";
getline(cin,str);
cout << "\nThe total number of String is : " << str << endl;
cout << count(str) << endl;

return 0;
}
You could look at std::sort and std::unique for inspiration.
Alternatively, std::unordered_set
One option:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
#include <set>

using namespace std;

typedef unsigned int uint;

uint CountUniqueChars (const string& input);

int main ()
{
  string str;
  cout << "** Welcome at the unique char counting program\n\n";
  cout << "** Enter a string: ";
  getline (cin, str);
  cout << "\nNumber of unique chars: " << CountUniqueChars (str) << "\n\n";
  
  system ("pause");
  return 0;
}

uint CountUniqueChars (const string& input)
{
  set<char> uniqueChars;
  for (char ch : input)
  {
    if (uniqueChars.find (ch) == uniqueChars.end()) // Not in the set 
    { 
      uniqueChars.insert (ch); // ok add it
    }
    else
    {
      uniqueChars.erase (ch); // already there so it's not unique anymore - remove it
    }
  }
  return uniqueChars.size ();
}
Thomas1965 wrote:
One option:

Just an observation: Any character with an odd number of appearances will be considered unique, and any character with an even number of appearances will not be considered at all, whereas the OP calls for the size of the string less the number of duplicate characters.
@cire,

you are right, somehow I misunderstood the OP.
I made this code:
It counts repeated characters as 1, and doesn't include space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<string.h>
using namespace std;
int main(){
    cout<<"Enter your string: ";
    char str[100];
    cin.getline(str,100);
    int c=0;
    for(int d=0; str[d]!='\0';d++)
        if(str[d]!=' ')
            c++;
    for(unsigned int i=0; i<strlen(str)-1;i++){
            if(str[i]!=' '){
        for(int j=i+1; str[j]!='\0';j++){
            if(str[i]==str[j]){
               c--;
               i++;
                }
            }
        }
    }
    cout<<c<<endl;
    return 0;
}
Topic archived. No new replies allowed.