Home >Backend Development >C#.Net Tutorial >C language strchr function usage

C language strchr function usage

Guanhui
GuanhuiOriginal
2020-06-15 11:47:257449browse

C language strchr function usage

C语言 strchr 函数用法

C语言中strchr函数作用是为在一个串中查找给定字符的第一个匹配之处,该函的原型为“char *strchr(const char *str, int c)”,使用时向str传入要被检索的字符串,c传入要搜索的字符即可。

演示实例

#include <stdio.h>
#include <string.h>

int main ()
{
   const char str[] = "http://www.runoob.com";
   const char ch = &#39;.&#39;;
   char *ret;

   ret = strchr(str, ch);

   printf("|%c| 之后的字符串是 - |%s|\n", ch, ret);
   
   return(0);
}

编译后运行结果:

|.| 之后的字符串是 - |.runoob.com|

使用示例

//#define  FIRST_DEMO
#define  SECOND_DEMO
#ifdef FIRST_DEMO
#include <stdio.h>
#include <conio.h>
#include <string.h>
#pragma warning (disable:4996)
int main(void)
{
	char string[17];
	char *ptr;
	char c=&#39;T&#39;;
	strcpy(string,"This is a string");
	ptr=strchr(string,c);
	if (ptr)
	{
		printf("The character %c is at position:%d\n",c,ptr-string);
	}
	else
	{
		printf("The character was not found\n");
	}
	getch();
	return 0;
}
#elif defined SECOND_DEMO
#include <stdio.h>
#include <conio.h>
#include <string.h>
#pragma warning (disable:4996)
int main(void)
{
    char answer[100];
	char *p;
	printf("Type something:\n");
	fgets(answer,sizeof answer,stdin);
	if ((p=strchr(answer,&#39;\n&#39;))!=NULL)   /*fgets不会像gets那样自动地去掉结尾的\n,所以程序中手动将\n位置处的值变为\0,代表输入的结束。*/
	{
		*p=&#39;\0&#39;;
	}
	printf("You typed \"%s\"\n",answer);
	getch();
	return 0;
}
#endif


推荐教程:《C#

The above is the detailed content of C language strchr function usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn