strncmp用法示例
时间: 2023-09-07 12:16:51 浏览: 228
strcmp 函数的使用
strncmp函数用于比较两个字符串的前n个字符是否相等。它的函数声明为int strncmp(const char *str1, const char *str2, size_t n)。 示例用法如下:
```C
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Help";
int result = strncmp(str1, str2, 3);
if (result == 0) {
printf("The first 3 characters of str1 and str2 are the same.\n");
} else if (result < 0) {
printf("The first 3 characters of str1 are less than str2.\n");
} else {
printf("The first 3 characters of str1 are greater than str2.\n");
}
return 0;
}
```
在这个示例中,我们比较了字符串"Hello"和"Help"的前3个字符。由于两个字符串的前3个字符都是"H", "e", "l",因此它们是相等的。结果会打印出"The first 3 characters of str1 and str2 are the same."。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [strncmp函数用法详解](https://blog.csdn.net/weixin_31596631/article/details/115151520)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文