有一個名爲strncasecmp
函數,而不是存在於所有系統(我是一個Linux用戶),因爲不是標準功能:
int strncasecmp(const char *s1, const char *s2, size_t n);
功能看起來是這樣的,如果不存在在你的系統:
int strncasecmp(char *s1, char *s2, size_t n){
if (n == 0){
return 0;
}
while (n-- != 0 && tolower(*s1) == tolower(*s2)){
if (n == 0 || *s1 == '\0' || *s2 == '\0'){
break;
}
s1++;
s2++;
}
return tolower(*(unsigned char *) s1) - tolower(*(unsigned char *) s2);
}
,你可以使用它像這樣:
#include <stdio.h>
#include <strings.h>
int main(void){
char *user_input = "yes";
char *ch = "Y";
if (strncasecmp(user_input, ch, 1) == 0){
printf("True\n");
}else{
printf("False\n");
}
return 0;
}
正如你可以看到有與區分大小寫沒有問題。該strncasecmp
功能在strings.h
發現,而不是在string.h
是否有可能增加一個問號(?)的用戶,如果用戶忘記添加一個?
是的,你可以。下面這段代碼是一種方式來幫助你瞭解如何做到這一點:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
char *question = "What is your Question";
size_t length = strlen(question);
char *addQuestion = malloc(length + 2);
memcpy(addQuestion,question,length + 1);
printf("Before\n%s\n",addQuestion);
strcat(addQuestion, "?");
printf("\n");
printf("After\n%s\n",addQuestion);
free(addQuestion);
return 0;
}
輸出:
Before
What is your Question
After
What is your Question?
是否足夠好,它帶有Y開頭或它必須是你列出的單詞? –