C庫函數int strncmp(const char *str1, const char *str2, size_t n)最多比較前 n 個字節str1和str2。
字符數組稱為字符串。
聲明
聲明數組的語法如下 -
char stringname [size];
例如 - char string[50];長度為 50 個字符的字符串
初始化
- 使用單字符常量 -
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
- 使用字符串常量 -
char string[10] = "Hello":;
Accessing− 有一個控製字符串 "%s" 用於訪問字符串,直到遇到“\0”。
strncmp ( ) 函數
該函數用於比較 2 個字符串的前 ‘n’ 個字符。
用法
strncmp() 函數的語法如下 -
strncmp ( string1, string2, n)
示例
char a[10] = "the";
char b[10] = "there"
strncmp (a,b,3);
輸出將是兩個字符串相等。
示例
下麵給出的是一個 C 程序,它使用 strncmp 庫函數比較兩個字符串之間的特定字符 -
#include<stdio.h>
#include<string.h>
void main(){
//Declaring two strings//
char string1[25],string2[25];
int value;
//Reading string 1 and String 2//
printf("Enter String 1:");
gets(string1);
printf("Enter String 2:");
gets(string2);
//Comparing using library function//
value = strncmp(string1,string2,4);
//If conditions//
if(value==0){
printf("%s is same as %s",string1,string2);
}
else if(value>0){
printf("%s is greater than %s",string1,string2);
} else {
printf("%s is less than %s",string1,string2);
}
}
輸出
執行上述程序時,會產生以下結果 -
Run1: Enter String 1:Welcome Enter String 2:TO my World Welcome is greater than TO my World Run 2: Enter String 1:welcome Enter String 2:welcome welcome is same as welcome
相關用法
- C語言 strncat()用法及代碼示例
- C語言 strncpy()用法及代碼示例
- C語言 strnset()用法及代碼示例
- C語言 strcspn()用法及代碼示例
- C語言 strtol()用法及代碼示例
- C語言 strrchr()用法及代碼示例
- C語言 strftime()用法及代碼示例
- C語言 strtok()用法及代碼示例
- C語言 strupr()用法及代碼示例
- C語言 strlen()用法及代碼示例
- C語言 strtod()用法及代碼示例
- C語言 strspn()用法及代碼示例
- C語言 strstr()用法及代碼示例
- C語言 strcat()用法及代碼示例
- C語言 strxfrm()用法及代碼示例
- C語言 strchr()用法及代碼示例
- C語言 strrev()用法及代碼示例
- C語言 strcmpi()用法及代碼示例
- C語言 strtok()、strtok_r()用法及代碼示例
- C語言 strerror()用法及代碼示例
注:本文由純淨天空篩選整理自Bhanu Priya大神的英文原創作品 What is strncmp() Function in C language?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。