布尔 C 字符串序列 - 报告匹配项

boolean c-string sequence - reporting a match

本文关键字:报告 字符串 布尔      更新时间:2023-10-16

如果我有一个布尔原型,例如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] 等继续在数组中查找吗?

任何见解都值得赞赏。 谢谢。

首先,您必须更改条件

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 数组的大小",则此代码将在修复相等运算符后起作用。

这是

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;
}
首先使用 == 进行比较,

而不是使用 = ,后者用于赋值。

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

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

由于 c 中的字符串''终止,因此请使用 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;
}

注意:我已经尝试了此代码。