做
if(strncmp(buf, buf2, 7) == 0)
Run Code Online (Sandbox Code Playgroud)
做同样的事情
if(memcmp(buf, buf2, 7) == 0)
Run Code Online (Sandbox Code Playgroud)
buf和buf2是 char* 数组或类似数组。
我本来打算将其附加到另一个问题中,但后来决定也许最好单独发布。大概答案是微不足道的“是”,或者如果不是,那么有什么区别呢?
(我从在线文档中找到了这些函数,但不确定,strncmp因为文档有点不清楚。)
我有两个字符串要比较,我认为使用strncmp会比使用更好,strcmp因为我知道其中一个字符串长度.
char * a = "hel";
char * b = "he"; // in my real code this is scanned so it user dependent
for(size_t i = 0; i < 5; i++){
printf("strncmp: %d\n", strncmp(a,b,i));
}
Run Code Online (Sandbox Code Playgroud)
我期待输出
0
0
0
1 // which is the output of printf("strcmp: %d\n", strncmp(a,b));
1
Run Code Online (Sandbox Code Playgroud)
因为只在第4次迭代(i = 3)中,字符串开始不同,但我得到了
0
0
0
108 // guessing this is due to 'l' == 108 in ascii
108
Run Code Online (Sandbox Code Playgroud)
我不明白为什么,正如男人所说:
该
strcmp() …
我正在尝试将来自iphone应用程序的用户文本输入与我声明的静态数组中的文本进行比较.它总是返回"真实",即使文本不同.执行strncmp后,我会显示两个文本字段.对于人眼来说,它们就是我所期待的领域.我返回到屏幕的debugmsg显示了我期望的值,但比较始终是真实的.任何建议,将不胜感激.谢谢.
if (strncmp(SymbolEntered.text,
[NSString stringWithCString:elements_table2[idx].element_symbol],2)==0)
{
DebugMsg.text = [NSString stringWithCString:"Correct answer"];
}
else
{
DebugMsg.text = [NSString stringWithCString:"Incorrect!"];
}
DebugMsg2.text = SymbolEntered.text;
DebugMsg3.text = [NSString stringWithCString:elements_table2[idx].element_symbol];
Run Code Online (Sandbox Code Playgroud) 我正在编程一个锁,在哪里解锁它你必须在键盘中插入一个 PIN 码。我有以下变量:
char password_init[4] = {'1', '2', '3', '4'}; //initial password
char password[4];
Run Code Online (Sandbox Code Playgroud)
当用户按下键盘上的某个键时,该数字将存储在变量中,password并且在用户按下 4 位数字后,将比较两个变量,以确定是否可以访问锁定。
我发现这样做的一种解决方案是使用 strncmp() 函数:
if (!(strncmp(password, password_init, 4))){
Serial.println("PIN Code correct");
}
Run Code Online (Sandbox Code Playgroud)
这有效,但我不明白为什么我应该使用!(strncmo())而不是strncmo(). 如果我使用if (strncmp(password, password_init, 4)),结果将是错误的 PIN 码。
该strncmp()函数逐个字符地比较两个字符串,所以有人可以解释我为什么必须以否定方式使用它来代替初始密码和用户在键盘匹配中按下的密码吗?