how to find total numbe of distinct characters in a string in c
To find the total number of distinct characters in a string in C++, you can follow these steps:
Declare an integer variable
count
and initialize it to 0. This variable will keep track of the number of distinct characters.Declare a Boolean array
charSet
of size 256 (assuming ASCII characters) and initialize all its elements tofalse
. This array will help us keep track of which characters have been encountered before.Iterate through each character in the string. You can do this using a
for
loop or awhile
loop. Let's assume the string is stored in a variable calledstr
.Inside the loop, check if the current character
str[i]
has been encountered before by accessing the corresponding index in thecharSet
array. IfcharSet[str[i]]
isfalse
, it means this character is encountered for the first time.If the character is encountered for the first time, set
charSet[str[i]]
totrue
to mark it as encountered and increment thecount
variable by 1.After the loop ends, the value of
count
will be the total number of distinct characters in the string.
Here is the code snippet that implements the above steps:
int countDistinctCharacters(const std::string& str) {
int count = 0;
bool charSet[256] = {false};
for (int i = 0; i < str.length(); ++i) {
if (charSet[str[i]] == false) {
charSet[str[i]] = true;
count++;
}
}
return count;
}
You can call the countDistinctCharacters
function and pass your string as an argument to get the total number of distinct characters.