How do you break a long string into words and iterate through each character of word and if they match increment a char count using stringstream

Viewed 36
int MatchString::comparsion(string newq, string oldq){
//breaks down the string into the smaller strings
stringstream s1(newq);
stringstream s2(oldq);

string new_words;
string old_words;

int word_count = 0;

while(s1>>new_words&&s2>>old_words){
    for(int i = 0; i<new_words.length();i++){
        for(int j = 0; j<old_words.length();j++){
            char a = new_words[i];
            char b = old_words[j];
            if(a == b){
                char_count++;
            }
            else{
                j++;
            }
        }//end of 2nd for
    }//end of for
}
return char_count;

}

I'm currently trying to make a function that takes in two strings and breaks them down into words then into chars. Afterward, I try to compare the value of each char and see if they equal each other. And if they do I increment a char_count by 1. Else I increment j so I compare next char in string 2 with string 1. I need to use this char_count value later to develop another algorithm because I need it to calculate a percentage difference between the two strings which is why I return it at the end because including that calculation with this method would be a bit messy. However when cout the return value I get something completely wrong. I don't know what I'm doing wrong can you please help.

1 Answers

Your j++ under else in the for-loop is redundant, if I'm correct. Allow your for-loop to naturally advance its iterator, don't force it within else{}.

Related