如何将长字符串分解为单词并迭代单词的每个字符,如果它们匹配则使用 stringstream 增加字符计数

发布于 2025-01-16 09:35:30 字数 924 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

耶耶耶 2025-01-23 09:35:30

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

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{}.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文