[英]Compare string byte against char c++
我想要的是遍歷一個字符串,然后針對該字符串中的每個字符,將其與某個字符(例如“ M”)進行比較。 std::string::find
對我不起作用,因為字符在字符串中出現的順序很重要(例如,羅馬數字MC與CM不同)。
我得到的代碼(我正在使用c ++ 11進行編譯):
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
string str = ("Test Mstring");
for (auto it = str.begin(); it < str.end(); it++) {
if (strcmp(*it, "M") == 0) cout << "M!1!!1!" << endl;
}
}
控制台錯誤顯示:
test.cc: In function ‘int main()’:
test.cc:10:16: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
if (strcmp(*it, "M") == 0) cout << "M!1!!1!" << endl;
^~~
In file included from /usr/include/c++/7/cstring:42:0,
from test.cc:2:
/usr/include/string.h:136:12: note: initializing argument 1 of ‘int strcmp(const char*, const char*)’
extern int strcmp (const char *__s1, const char *__s2)
解引用從std::string
獲得的迭代器將返回char
。 您的代碼只需要是:
if (*it == 'M') cout << "M!1!!1!" << endl;
也:
注意'M'!=“ M。 在C ++中,雙引號定義了一個字符串文字,該字符串以一個空字節終止,而單引號則定義了一個字符。
除非打算刷新標准輸出緩沖區,否則不要使用endl
。 \\n
快很多。
C ++中的strcmp
通常是代碼異味。
字符串的元素是字符,例如'M'
,而不是字符串。
string str = "Test Mstring";
for (auto it = str.begin(); it < str.end(); it++) {
if (*it == 'M') cout << "M!1!!1!" << endl;
}
要么
string str = "Test Mstring";
for (auto ch: str) {
if (ch == 'M') cout << "M!1!!1!" << endl;
}
strcmp
比較整個字符串,因此,如果您比較"mex"
與"m"
,他們是不相等的,你不能比較char
以char
從string
在此功能,因為比較字符,你可以使用字符串作為數組,如
string c = "asd";
string d = "dss";
if(c[0]==d[0] /* ... */
if(c[0]=='a') /*... */
請記住, it
是字符串中指向char的指針,因此在取消引用時,必須與char比較
if(*it=='c')
順便說一句,為什么要混合使用C和C ++字符串? 您可以像在C ++中一樣使用string
,但是函數strcmp
來自C庫
您可以執行以下操作:
std::for_each(str.begin(), str.end(), [](char &c){ if(c == 'M') cout<< "M!1!!1!"<<endl; });
迭代器指向字符串變量中的char,而不必進行字符串比較
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.