2017-06-22 38 views
0
int main() 
{ 
char *a = "i am mad"; 
string str(a); 
cout<<str.rfind("mad"); 

system("pause"); 
return 0; 
} 

所以我想比较的string.Let的一个特定部分说字符串包含mad那么我会执行一些操作,如果没有,我会进行一些其他的操作。我的源字符串仅以const char格式存在。 我能够找到子字符串的位置,即mad,但我不能用它来比较某些东西。比较字符串的特定部分用另一个字符串

这是我如何找到子字符串的位置,但我不知道如何比较。 我应该改变什么? 我知道mad从第5个位置开始,但是我该如何比较。

+0

我对编程相当新。你能告诉我怎么做吗? –

回答

0

您需要对rfind()的结果进行比较。

int main() 
{ 
    const char *a = "i am mad"; 
    string str(a); 

    if (str.rfind("mad") == string::npos) // string::npos means not found, according to the docs 
    { 
     cout << "All is well" << endl; 
    } 
    else 
    { 
     cout << "Uh oh, somebody's mad!" << endl; 
    } 

    system("pause"); 
    return 0; 
} 
0

如果你能够找到一个疯狂的起始索引,然后从它创建一个substr。 STR2 = str.substr(起始指数“疯狂”,长度“疯”)

那么你可以使用STR2与其他

0

来比较,你可以比较字符串::非营利组织收益指数

int ret = str.rfind("mad", str.length()); 
if (ret != string::npos) 
{ 
    // mad found in str 
} 
else 
{ 
    // mad not found 
}