首页 > 解决方案 > 如何检查两个字符串是否“不管一个字符”是否相等?

问题描述

我想检查两个字符串是否相等,无论缺少一个字符。例如“HappyMan”等于“HappyMn”和“HappyMann”和“HappyMnn”。是否有任何内置功能来执行此任务?我试图对它们进行排序,然后计算有多少字符不同,但它不起作用。这是我的代码

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>

using namespace std;

int main() {
    string a, b;
    cin >> a >> b;
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    int cnt = 0;
    for (int i = 0; i < a.length(); i++) {
        if (a[i] != b[i])
            cnt++;
        if (cnt > 1) {
            cout << "Not equal";
            return 0;
        }
    }
    cout << "Equal";

    return 0;
}

标签: c++

解决方案


#include <iostream>
#include <string>
int main()
{
  std::string str1 = "manatee";
  std::string str2 = "mannatee";

  std::string strLong = "";
  std::string strShort = "";

  if (str1.length() >= str2.length()){
      strLong = str1;
      strShort = str2;
  }
  else{
      strLong = str2;
      strShort = str1;
  }

  if (strLong.length() - strShort.length() > 1){
      printf("%s", "They are not equal.");
      return false;
  }

  bool firstDifference = true;

  for (int i = 0; i < strShort.length(); i++){
    if (strShort[i] != strLong[i] && firstDifference){
        if (strLong.length() > strShort.length()){
            strLong = strLong.substr(0, i) + strLong.substr(i+1, strLong.length() - i 
            - 1);
        }
        firstDifference = false;
        continue;
    }
    else if (strShort[i] != strLong[i] && !firstDifference) {
        printf("%s", "They are not equal");
        return false;
    }    
  }

  printf("%s", "They are equal");
  return true;

}

推荐阅读