I have an array of strings (ex: string dna[50]) that is holding up to fifty 10 character strings. I am trying to compare each character of each string in the array to a separate single string, also 10 characters. However, I can't seem to figure out how to iterate through each character in order to compare each letter. I feel like I am doing something wrong on line 13, but I am really not sure. C++ newbie here, and any help would be greatly appreciated! Cheers!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void displayPercent(string myDna, string dnaOfPeople[],
string namesOfPeople[], int numberOfPeople, int percentArray[])
{
int i = 0;
int j = 0;
int counter = 0;
int percentage = 0;
for (i = 0; i < numberOfPeople; i++) //loops as many times as the number of people we are comparing
{
for (j = 0; j < 10; j++) //loops through all 10 characters of each string in array
{
if (dnaOfPeople[i][j] == myDna[j]) //compares the value of string i and character j to the chars in my string
{
counter++; //adds to a counter each time a character is the same
}
}
cout << "Percent match for " << namesOfPeople[i] << ": " << counter * 10 << "%" << endl;
}
}
On outer layer you have a list of words and a token word.
1 2 3 4 5
std::vector<std::string> words;
std::string token;
for ( auto word : words ) {
// compare token and word
}
How to compare two words is a separate task. You could have that in a separate function.
A simpler 100% or not:
1 2 3 4
bool allornothing( const std::string& me, const std::string& you ) {
if ( me.size() != you.size() ) returnfalse; // size mismatch, will not compare
return me == you;
}
Count of matches:
1 2 3 4 5 6 7 8
int match( const std::string& me, const std::string& you ) {
if ( me.size() != you.size() ) return 0; // size mismatch, will not compare
int count = 0;
for ( size_t b=0; b < me.size(); ++b ) {
if ( me[b] == you[b] ) ++count;
}
return count;
}
For fun, peek at: http://www.cplusplus.com/reference/numeric/inner_product/
It is somewhat similar, for in it each pair can contribute to the count, just like here.
One could replace the match() with inner_product, if one uses custom "multiplication".
Back to the list:
1 2 3 4 5
std::vector<std::string> words;
std::string token;
for ( auto word : words ) {
std::cout << match( token, word ) << '\n';
}