b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

【库函数源码分析系列】(6) strchr

电脑杂谈  发布时间:2019-08-22 13:03:27  来源:网络整理

strchr函数怎么用_c strchr函数用法_strchr函数怎么用

strchr:

strchr函数怎么用_strchr函数怎么用_c strchr函数用法

// strchr
#include <stdio.h>
char *Strchr(const char *s, int c)
{
	for (; *s != (char)c; ++s) {
		if (*s == '\0') {
			return NULL;
		}
	}
	
	return (char *)s;
}
int main( int argc, char **argv )
{
	char string[] = "The quick brown dog jumps over the lazy fox";
	char fmt1[] =   "         1         2         3         4         5";
	char fmt2[] =   "12345678901234567890123456789012345678901234567890";	
	char *pdest = NULL;
	int result;
	char ch;
	printf( "String to be searched: \n\t\t%s\n", string );
	printf( "\t\t%s\n\t\t%s\n\n", fmt1, fmt2 );
	
	ch = 'r';
	printf( "Search char:\t%c\n", ch );	
	pdest = Strchr( string, ch );
	result = pdest - string + 1;
	if( pdest != NULL )
		printf( "Result:\tfirst %c found at position %d\n\n", 
		ch, result );
	else
		printf( "Result:\t%c not found\n" );
	
	ch = '\0';	// 测试特殊字符
	printf( "Search char:\t%c(此处是\'\\0\',不可显示)\n", ch );	
	pdest = Strchr( string, ch );
	result = pdest - string + 1;
	if( pdest != NULL )
		printf( "Result:\tfirst %c found at position %d\n\n", 
		ch, result );
	else
		printf( "Result:\t%c not found\n" );
	
	return 0;
}

strchr函数怎么用_c strchr函数用法_strchr函数怎么用

1、当传入的指针是NULL时,函数中是没有检查的。

strchr函数怎么用_c strchr函数用法_strchr函数怎么用

2、注意当查找的字符是’\0′时strchr函数怎么用,应该总是找得到的!返回的是字符串尾’\0′的地址,不过想想strchr函数怎么用,返回这个指针还有什么用呢?没什么实际含义啊。这一点也导致strchr函数极易漏掉,比如:

c strchr函数用法_strchr函数怎么用_strchr函数怎么用

char *Strchr(const char *s, int c)
{
	while (*s != '\0' && *s != (char)c)
		s++;
	
	if (*s == '\0')
		return NULL;
	
	return (char *)s;
}

上面的程序是错的,就是因为当查找的是’\0′时,它觉得是到达了字符串尾,却没想到’\0′使while的两个条件同时为假了!这种错误得切记。所以应改为:

char *Strchr(const char *s, int c)
{
	while (*s != '\0' && *s != (char)c)
		s++;
	
	if (*s == (char)c)
		return (char *)s;
	return NULL;
}

必须先测试是不是找到了c。


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-120169-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...