C 語言中的 strncmp() 函式是什麼?
C 庫函式 int strncmp(const char *str1, const char *str2, size_t n) 最多比較 str1 和 str2 前 n 個位元組。
字元陣列稱為字串。
宣告
宣告陣列的語法如下 −
char stringname [size];
例如 − char string[50];長度為 50 個字元的字串
初始化
- 使用單個字元常量 −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}- 使用字串常量 −
char string[10] = "Hello":;
訪問 − 有一個控制字串 "%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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP