C++
字符串 | Strings

std::strncmp

STD:斯特恩西姆

Defined in header
int strncmp( const char* lhs, const char* rhs, size_t count

最多比较count两个以空结尾的字节字符串的字符。比较是按字典顺序进行的。

结果的符号是第一对字符%28的值之间差值的符号,这两个字符都被解释为unsigned char%29,在所比较的字符串中存在差异。

如果lhsrhs不是指向以空结尾的字符串的指针。

不对空字符后面的字符进行比较。

参数

lhs, rhs-pointers to the null-terminated byte strings to compare
count-maximum number of characters to compare

返回值

负值lhs出现在前面rhs按字典顺序排列。

零中频lhsrhs比较平等。

正值lhs出现在rhs按字典顺序排列。

二次

#include <cstring> #include <iostream> void demo(const char* lhs, const char* rhs, int sz) { int rc = std::strncmp(lhs, rhs, sz if(rc == 0) std::cout << "First " << sz << " chars of [" << lhs << "] equal [" << rhs << "]\n"; else if(rc < 0) std::cout << "First " << sz << " chars of [" << lhs << "] precede [" << rhs << "]\n"; else if(rc > 0) std::cout << "First " << sz << " chars of [" << lhs << "] follow [" << rhs << "]\n"; } int main() { demo("Hello, world!", "Hello, everybody!", 13 demo("Hello, everybody!", "Hello, world!", 13 demo("Hello, everybody!", "Hello, world!", 7 demo("Hello, everybody!" + 12, "Hello, somebody!" + 11, 5 }

二次

产出:

二次

First 13 chars of [Hello, world!] follow [Hello, everybody!] First 13 chars of [Hello, everybody!] precede [Hello, world!] First 7 chars of [Hello, everybody!] equal [Hello, world!] First 5 chars of [body!] equal [body!]

二次

另见

strcmpcompares two strings (function)
wcsncmpcompares a certain amount of characters from two wide strings (function)
memcmpcompares two buffers (function)
strcollcompares two strings in accordance to the current locale (function)

c strncmp文档

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/string/字节/strncmp