将字符串字节与字符 c++ 进行比较

Compare string byte against char c++

本文关键字:比较 c++ 字符 字符串 字节      更新时间:2023-10-16

我想要的是遍历一个字符串,对于这个字符串中的每个字符,将其与某个字符进行比较,例如"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"进行比较,它们是不相等的,你不能在这个函数中将charstringchar进行比较,因为要比较字符,你可以使用字符串作为数组,例如

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; });

迭代器指向字符串变量中的字符,您不必进行字符串比较