hgj125073的专栏

不要急,慢慢来。

C语言之strchr函数

【FROM MSDN && 百科】

原型: char *strchr(const char *s,char c);

#include<string.h>

查找字符串s中首次出现字符c的位置,返回首次出现c的位置的指针,如果s中不存在c则返回NULL

The strchr function finds the first occurrence of c instr, or it returns NULL ifc is not found. The null terminating character is included in the search.


DEMO:

//#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='T';
	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,'\n'))!=NULL)   /*fgets不会像gets那样自动地去掉结尾的\n,所以程序中手动将\n位置处的值变为\0,代表输入的结束。*/
	{
		*p='\0';
	}
	printf("You typed \"%s\"\n",answer);
	getch();
	return 0;
}
#endif


printf("The string is \"%s\"\n",ptr);

输出结果为:The string is "his is a string"

阅读更多
文章标签: c C strchr string String
个人分类: Basic knowledge of C
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭