c++ check if string is isogram
To check if a string is an isogram in C++, you can follow these steps:
Declare a function named
isIsogram
that takes astd::string
as input and returns a boolean value.Inside the function, create a
std::unordered_set<char>
namedseenChars
. This set will be used to keep track of the characters we have seen so far in the string.Iterate over each character in the input string using a range-based for loop. For each character, do the following:
Convert the character to lowercase using the
std::tolower
function from the<cctype>
header. This step is optional if you want to consider both uppercase and lowercase letters as the same.Check if the character is already present in the
seenChars
set. If it is, returnfalse
because it means the string is not an isogram. Otherwise, add the character to theseenChars
set.After the loop, if we haven't returned
false
yet, it means that no duplicate characters were found in the string. In this case, returntrue
to indicate that the string is an isogram.
Here is an example implementation of the isIsogram
function:
#include <unordered_set>
#include <cctype>
bool isIsogram(const std::string& str) {
std::unordered_set<char> seenChars;
for (char c : str) {
c = std::tolower(c);
if (seenChars.count(c) > 0) {
return false;
}
seenChars.insert(c);
}
return true;
}
You can use this function to check if a given string is an isogram by calling isIsogram(str)
, where str
is the input string you want to check. The function will return true
if the string is an isogram, and false
otherwise.