获取数组长度,先计算数组的总字节大小,再除以单个元素字节数。与 python 不同的是,C 语言中数组存储的元素的类型和大小都是一样的。C 语言中,字符串实际都是字符数组,且字符串最后一个元素为 \0。
char sentences[][13] = {
"Hello world1",
"Hello world2",
"Hello world3",
"Hello world4",
"Hello world5",
"Hello world6"
};
int sentence_num = sizeof(sentences) / sizeof(sentences[0]);
通过 fgets 获取输入字符串,假如输入Hello world1
,实际 search_for 指向的字符数组为 Hello world1\n\0
,包括额外的\0
和换行符这两个字符。而 strlen 计算字符串长度时,是排除结尾的\0
后的长度,即Hello world\n
的长度 。所以search_for[strlen(search_for) - 1]
实际是Hello world1\n\0
倒数第二个元素,替换后字符串为Hello world1\0\0
。
char search_for[14];
printf("Search for: ");
fgets(search_for, 14, stdin);
printf("%i\n", strlen(search_for));
search_for[strlen(search_for) - 1] = '\0';
printf("%s\n", search_for);
find_sentence(search_for);
strstr 要求查找的子串以\0
结尾,以便获取子串的长度,但测试不以\0
结尾也能正常查找。
char search_for2[] = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '1'};
strstr(sentences[0], search_for2);
代码:
#include <stdio.h>
#include <string.h>
char sentences[][13] = {
"Hello world1",
"Hello world2",
"Hello world3",
"Hello world4",
"Hello world5",
"Hello world6"
};
int sentence_num = sizeof(sentences) / sizeof(sentences[0]);
void find_sentence(char search_for[]){
int i;
for(i = 0; i < sentence_num; i++){
if(strstr(sentences[i], search_for)){
printf("sentence %i: %s\n", i, sentences[i]);
}
}
}
int main(){
char search_for[14];
printf("Search for: ");
fgets(search_for, 14, stdin);
printf("%i\n", strlen(search_for));
search_for[strlen(search_for) - 1] = '\0';
printf("%s\n", search_for);
find_sentence(search_for);
//char search_for2[] = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '1'};
//find_sentence(search_for2);
return 0;
}