在C++中,如何在 C 中使用 strncmp 函数?

In C++, how do i use like strncmp function in C?

本文关键字:strncmp 函数 C++      更新时间:2023-10-16

在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。如果第一个字符串小于第二个字符串,则该函数返回负值。否则,该函数返回正值。