一、使用strchr函數判斷
在C語言中,我們可以使用strchr庫函數來查找一個特定的字符是否在一個字符串中存在。strchr函數的原型在string.h頭文件中聲明為:
char* strchr(const char* str, int c);
其中str為要查找的字符串,c是要查找的字符。
如果該字符未在字符串中找到,則返回NULL,否則返回該字符在字符串中的位置。
代碼示例:
#include <stdio.h>
#include <string.h>
int main(){
char str1[] = "Hello, world!";
if (strchr(str1, 'o') != NULL) {
printf("The character o is found.\n");
}
else {
printf("The character o is not found.\n");
}
return 0;
}
輸出結果:
The character o is found.
二、使用while循環遍歷字符串
我們也可以使用while循環來遍歷字符串,逐個比較其中的每一個字符是否是我們要查找的字符。
代碼示例:
#include <stdio.h>
#include <string.h>
int main(){
char str1[] = "Hello, world!";
char c = 'o';
int flag = 0;
int i = 0;
while (str1[i] != '\0') {
if (str1[i] == c) {
flag = 1;
break;
}
i++;
}
if (flag == 1) {
printf("The character %c is found.\n", c);
}
else {
printf("The character %c is not found.\n", c);
}
return 0;
}
輸出結果:
The character o is found.
三、使用strstr函數判斷
除了strchr函數外,我們還可以使用strstr函數查找一個字符串中是否包含另一個字符串。strstr函數的原型在string.h頭文件中聲明為:
char* strstr(const char* str1, const char* str2);
其中,str1是要查找的字符串,str2是要查找的子字符串。
如果子字符串未在父字符串中找到,則返回NULL,否則返回子字符串在父字符串中的位置。
代碼示例:
#include <stdio.h>
#include <string.h>
int main(){
char str1[] = "Hello, world!";
char str2[] = "wor";
if (strstr(str1, str2) != NULL) {
printf("The substring %s is found.\n", str2);
}
else {
printf("The substring %s is not found.\n", str2);
}
return 0;
}
輸出結果:
The substring wor is found.
四、使用自定義函數實現判斷
在C語言中,我們也可以通過自定義函數來實現判斷目標字符是否在字符串中存在的功能。
代碼示例:
#include <stdio.h>
#include <string.h>
int isInString(char str[], char c);
int main(){
char str1[] = "Hello, world!";
char c = 'o';
if(isInString(str1, c)){
printf("The character %c is found.\n", c);
}
else{
printf("The character %c is not found.\n", c);
}
return 0;
}
int isInString(char str[], char c){
int i = 0;
while(str[i] != '\0'){
if(str[i] == c){
return 1;
}
i++;
}
return 0;
}
輸出結果:
The character o is found.
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/234023.html