将字符串字节与字符 c++ 进行比较
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
与string
的char
进行比较,因为要比较字符,你可以使用字符串作为数组,例如
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; });
迭代器指向字符串变量中的字符,您不必进行字符串比较
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- shell排序中的交换和比较
- 如何在C++中比较两个char数组
- catch框架有没有办法比较流或文件
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 智能指针作为无序映射键,并通过引用进行比较
- 比较if语句中的数组值和int值
- 对于循环变体比较
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 比较两个大小不等的映射c++