编写一个名为find_mismatch的函数,它接受两个字符串作为输入参数

时间:2016-03-20 04:55:17

标签: c++

我正在尝试编写此功能,但我被卡住了。只是想在春假做一些练习。如果任何人有一个全新的方法,我是开放的。我知道这段代码是一个悲伤的景象,但我无法绕过它。提前谢谢。

    如果两个字符串完全匹配,则
  • 0。
  • 1如果两个字符串长度相同且仅在一个字符中不匹配。
  • 2如果两个字符串的长度不同或两个或多个字符不匹配。

代码:

void findMismatch (const string s1, const string s2)

    {int count;
if (s1.length() != s2.length())

     {
        cout <<"2"<< endl;
     }
if (s1 == s2)

    {
        cout <<"0"<< endl;
    }

1 个答案:

答案 0 :(得分:0)

这是我放在一起的解决方案。

#include <iostream>
#include <string>

using namespace std;
void findMismatch(string s1, string s2)
{   

    if(s1.length() != s2.length())
    {
        cout<<"2"<<endl;
    }
    else if(s1 == s2) //exact match
    {
        cout<<"0"<<endl;
        return;
    }
    else
    {

        int mismatchCount = 0;
        int i = 0;
        while(i < s1.length() && mismatchCount<=1)
        {
            if(s1.at(i) != s2.at(i) && ++mismatchCount == 2)
            {
                cout<<"2"<<endl;
                return;
            }
            i++;
        }
        cout<<"1"<<endl;
    }


}
int main()
{
  findMismatch("Achr","Acha"); //one mismatch
  findMismatch("Achrfs","Achaee"); //two or more mismatch
  findMismatch("Ach","Ach"); //exact match
  findMismatch("Achrfdfd","Acha"); //different lengths
}
相关问题