在C++中,如何在 C 中使用 strncmp 函数?
In C++, how do i use like strncmp function in C?
在C++中,不是有像strncmp()
那样的字符串函数吗 ???
例如
string str1 = "abc";
string str2 = "ab";
str2.compare(0,1,str1) == 0
可能吗??
您可以直接比较std::string
:
if (str1 == str2)
要比较长度为 2,请使用比较:
if (str2.compare(0, 2, str1) == 0)
如果包含相应的 C 标头,也可以在 C++ 中使用 C 函数,例如使用string.h
、 include<cstring>
。
std::string
重载了其"=="运算符。只是if (a == b)
有效。 有趣的是,甚至(a < b)
工作并应用词法排序。
编辑:由于TE似乎询问的是字符串长度的相等性,而不是它们的实际字母:
if (str1.length() == str2.length())
{
}
是的,类 std::string 具有为您声明的成员函数比较用例,例如
int compare(size_type pos1, size_type n1, basic_string_view<charT, traits> sv) const;
下面是一个演示程序,演示如何使用此重载成员函数。
#include <iostream>
#include <string>
int main()
{
std::string str1 = "abc";
std::string str2 = "ab";
std::cout << str2.compare( 0, 1 ,str1) << 'n';
std::cout << str1.compare( 0, 2 , str2) << 'n';
std::cout << str2.compare( str1 ) << 'n';
std::cout << str2.compare( 1, 1, str1 ) << 'n';
return 0;
}
程序输出为
-2
0
-1
1
因此,如果两个字符串相等,则函数返回 0。如果第一个字符串小于第二个字符串,则该函数返回负值。否则,该函数返回正值。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 在C++中,如何在 C 中使用 strncmp 函数?
- Arduino IDE 中使用 strncmp 函数时出错
- gdb-查找strncmp()函数的值
- C++ 上的 strncmp 函数