strcmp or string::compare?(strcmp 或 string::compare?)
问题描述
我想比较两个字符串.strcmp 可以吗?(我试过了,它似乎不起作用).string::compare 是解决方案吗?
I want to compare two strings. Is it possible with strcmp? (I tried and it does not seem to work). Is string::compare a solution?
除此之外,有没有办法将 string 与 char 进行比较?
Other than this, is there a way to compare a string to a char?
感谢您的早期评论.我用 C++ 编码,是的,就像你们中的一些人提到的那样,它是 std::string .我没有发布代码,因为我想学习一般知识并且它是一个很长的代码,所以它与问题无关.
Thanks for the early comments. I was coding in C++ and yes it was std::string like some of you mentioned.
I didn't post the code because I wanted to learn the general knowledge and it is a pretty long code, so it was irrelevant for the question.
我想我了解了 C++ 和 C 之间的区别,感谢您指出这一点.我现在将尝试使用重载运算符.顺便说一下 string::compare 也可以.
I think I learned the difference between C++ and C, thanks for pointing that out. And I will try to use overloaded operators now. And by the way string::compare worked too.
推荐答案
对于 C++,使用 std::string 并使用 string::compare 进行比较.
For C++, use std::string and compare using string::compare.
对于 C 使用 strcmp.如果您的(我的意思是您的程序)字符串(出于某种奇怪的原因)没有 nul 终止,请使用 strncmp 代替.
For C use strcmp. If your (i meant your programs) strings (for some weird reason) aren't nul terminated, use strncmp instead.
但是为什么有人不会为 std::string 使用像 == 这样简单的东西?
But why would someone not use something as simple as == for std::string
?
这篇关于strcmp 或 string::compare?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:strcmp 或 string::compare?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
