如何将一个长字符串分解为单词,并遍历单词的每个字符,如果它们匹配,则使用字符串流增加字符数


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;

}

我目前正在尝试制作一个函数,它接收两个字符串,并将它们分解为单词和字符。之后,我尝试比较每个字符的值,看看它们是否相等。如果他们这样做了,我会将char_count增加1。否则,我会增加j,以便将字符串2中的下一个字符与字符串1进行比较。稍后我需要使用这个char_count值来开发另一种算法,因为我需要它来计算两个字符串之间的百分比差,这就是为什么我在最后返回它,因为用这种方法进行计算会有点混乱。然而,当cout返回值时,我得到了一些完全错误的东西。我不知道我做错了什么,你能帮帮我吗。

如果我正确的话,for循环中else下的j++是多余的。允许for循环自然地推进其迭代器,不要在else{}中强制它。

最新更新