如何将长字符串分解为单词并迭代单词的每个字符,如果它们匹配则使用 stringstream 增加字符计数
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 值来开发另一个算法,因为我需要它来计算字符串之间的百分比差异两个字符串,这就是我最后返回它的原因,因为使用此方法包含该计算会有点混乱。然而,当计算返回值时,我得到了完全错误的结果。我不知道我做错了什么,你能帮忙吗?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我是正确的,for 循环中
else
下的j++
是多余的。让您的 for 循环自然地推进其迭代器,不要在else{}
中强制它。Your
j++
underelse
in the for-loop is redundant, if I'm correct. Allow your for-loop to naturally advance its iterator, don't force it withinelse{}
.