How to compare two strings that are different sizes
Lets just say string A = "ABCDEF"
, string B = "ABC"
Is there a way to compare both these strings character by character?
For example: Lets say you wanted to iterate through each string,
for(size of strings)
if(A.at(i) == B.at(i)
{
do something
}
else
{
do something else
}
You couldn't do it in a for loop since they're different sizes, any other suggestions?
You couldn't do it in a for loop since they're different sizes,
You absolutely can do it in a loop. You can use the following algorithm:
- Compare lengths of the strings
- Store the shorter length in
n
- Do
n
iterations in loop - Decide what you want to do with rest of the longer string
You could also take a look at something like std::lexicographical_compare
. It is used to sort words as they would be sorted in the dictionary. If you want to ensure that characters themselves are sorted in a different order, you can provide a function that does that comparison. For example, let's imagine that you want a letter 'c' to actually be sorted as a 'k'. You can accomplish that in the following manner:
bool comp(char c1, char c2)
{
c1 = std::tolower(c1);
c2 = std::tolower(c2);
c1 = (c1=='c') ? 'k' : c1;
c2 = (c2=='c') ? 'k' : c2;
return c1 < c2;
}
// main.cpp
std::string str1 = "string c";
std::string str2 = "string d";
std::string str3 = "string k";
std::cout << std::boolalpha;
std::cout << str1 << ( std::lexicographical_compare(str1, str2, comp) ? "<" : ">=" ) << str2 << std::endl;
std::cout << str1 << ( std::lexicographical_compare(str1, str3, comp) ? "<" : ">=" ) << str3 << std::endl;
std::cout << str2 << ( std::lexicographical_compare(str2, str3, comp) ? "<" : ">=" ) << str3 << std::endl;