【问题标题】:boolean c-string sequence - reporting a match布尔 c 字符串序列 - 报告匹配
【发布时间】:2016-09-18 20:03:34
【问题描述】:

如果我有一个布尔原型,例如bool repeat(const char *S, char *P) 我想在 S 中搜索与 P 相同的序列,如果匹配则返回 true,例如:

char *this = "ABCDEFGH";
bool found;
found = count(this, "DEF"); // will be true
found = count(this, "FED"); // will be false

我目前的幼稚解决方案是

bool count (const char *S, char *P){
bool found;
int i = 0;
if (S[0] = P[0] && S[1] = P[1] && S[2] = P[2]) found = true;
else i + 1;

如果第一个成员不匹配,我可以使用语法 S[0 + i] 等继续查找数组吗?

感谢任何见解。谢谢。

【问题讨论】:

  • char *this = "ABCDEFGH";?这合法吗?
  • @IInspectable 是的。见this post.
  • @AhmedAkhtar:不过,这个问题是关于c++,而this 是保留关键字。
  • @IInspectable 是的,你是对的。
  • @Lucas 看看我的答案,我已经发布了久经考验的工作代码。

标签: c++ arrays loops boolean sequence


【解决方案1】:

首先,你必须改变条件

if (S[0] = P[0] && S[1] = P[1] && S[2] = P[2])

到这里

if (S[0] == P[0] && S[1] == P[1] && S[2] == P[2])

因为您没有在第一个中使用相等运算符。它是赋值运算符,不返回真假。只需将第二个对象的值分配给第一个对象。

如果您只在第二个中搜索“大小为 3 的数组”,则此代码将在修复相等运算符后起作用。

【讨论】:

    【解决方案2】:

    首先使用==进行比较,而不是使用=进行赋值。

    其次不要使用this作为变量名,因为它是保留关键字。

    第三,对于这样的匹配,您需要遍历 char 数组,为此您首先需要找到它们的大小。

    由于c中的字符串是'\0'终止的,所以使用string.hstrlen函数来查找字符串的大小。

    #include <string.h>
    bool count (const char *S, char *P)
    {
     int sizeS = strlen(S);
     int sizeP = strlen(P);
    
     bool found = false;
    
     int i,j;
    
     for(i = 0; i < sizeS; i++)
     {
      if (S[i] == P[0])// step1: find first character of P in S
      {
       for(j = 1; j < sizeP; j++)// step2: first has matched, look for the rest
       {
        if(S[i+j] != P[j])// if any of the rest does not match, go on to step1
        {
         break;
        }
       }
       if(j == sizeP)// if all matched, j's loop did not break
       {
        found = true;
        break;
       }
      }
     }
     return found;
    }
    

    注意:我已尝试使用此代码。

    【讨论】:

    • SP 不是数组。它们是指针。表达式sizeof(S)/sizeof(S[0]) 不返回数组大小(或字符串长度)。此外,sizeof 运算符返回一个 std::size_t 类型的常量,而不是 int
    【解决方案3】:

    这是 C++,因此您可以使用 std::string。使用std::string 具有多重优势。

    其中一个是内置的std::string::find 方法,您可以使用它来查看字符串是否包含另一个:

    bool search(const std::string& S, const std::string& P)
    {
        return S.find(P) != std::string::npos;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-13
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 2015-02-07
      • 1970-01-01
      • 2022-10-15
      相关资源
      最近更新 更多