2016-05-21 54 views
-1

,如果我有一個布爾原型,如bool repeat(const char *S, char *P) 我要搜索S爲同一序列爲P,&返回true,如果有匹配,例如:布爾C-串序列 - 報告匹配

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]和等繼續尋找陣列中,如果第一構件不匹配?

任何洞察力是讚賞。謝謝。

+0

'char * this =「ABCDEFGH」;'?這甚至是合法的嗎? – IInspectable

+0

@IInspectable是的。看到[這篇文章。](http://programmers.stackexchange.com/questions/249554/assigning-strings-to-pointer-in-c) –

+0

@AhmedAkhtar:這個問題是關於[標籤:C++],雖然, 'this'是一個保留關鍵字。 – IInspectable

回答

3

首先,你因爲你沒有在第一次使用等於運算符來

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數組的大小',則此代碼將在修復相等運算符後生效。

1

這是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; 
} 
0

首先使用==進行比較,而不是=,這是任務。

其次不要使用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; 
} 

注:我已經試過這段代碼工作。

+0

'S'和'P'不是數組。他們是指針。表達式'sizeof(S)/ sizeof(S [0])'不返回數組大小(或字符串長度)。此外,'sizeof'運算符返回一個'std :: size_t'類型的常量,而不是'int'。 – IInspectable

+0

是的,我不得不使用'strlen'。現在就完成了。 –