C语言学习记录

获取数组长度,先计算数组的总字节大小,再除以单个元素字节数。与 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值