C语言中字符串处理函数

1.strchr

函数原型:extern char *strchr(const char *s,char c)
头文件:#include <string.h>
功能:查找字符串s中首次出现字符c的位置
说明:返回首次出现c的位置的指针,如果s中不存在c则返回NULL

上篇文章我们需要处理分隔一些命令来传递给一个指针数组,正好用到这个函数,so记录下来。
看代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#define MAXARGS   128
#define MAXLINE   1024

char * argv[MAXARGS];

/*Function prototypes */
int parseline( char * buf );

int main( )
{
	char  cmdline[MAXLINE]; /* Command line */

	while( 1 )
	{
		/* Read */
		printf( " >>" );
		fgets( cmdline, MAXLINE, stdin);
		if( feof ( stdin ) )
			exit( 0 );
		parseline( cmdline );
	}
	return 0;
}
int parseline( char * buf )
{
	int argc ; // record the number of argument
	char *delim;  //trace the  buf
	buf[strlen(buf) - 1] = ' ';// replace  '\0' with ' '

	int i;
	argc = 0;
	// ignore the space of command
	while( *buf && ( *buf == ' ' ) )
	{
        buf++;
	}
	while( ( delim = strchr( buf, ' ') ) )//find the address of space
	{
        argv[argc++] = buf;
        *delim = '\0';
        buf = delim + 1;// ignore the space of command
        while( *buf && ( *buf == ' ' ) )
        {
            buf++;
        }
	}
	argv[argc] = NULL;
	printf("the number of argument is %d\n", argc );
	for( i = 0; i < argc; i++ )
	{
        printf( "argc %d is %s\n", i , argv[i] );
	}
	return argc;
}


       代码实现功能:将命令 分隔开来,并存放到一个指针数组中
运行展示:
这里又学会了一种分隔字符串的处理函数, 
OK,下一个例子:
#include <stdio.h>
#include <string.h>
int  main()
{
    char input[100];
    printf("Type something:\n");
    fgets(input,sizeof ( input ),stdin);

    printf("You typed \"%s\"\n",input);
    return 0;
}

打印输出结果:

这里打印输出的时候把    '\n'也打印出来,那么如何去掉呢,用我们刚才所学的函数修改下代码就好了。
#include <stdio.h>
#include <string.h>
int  main()
{
    char input[100],*p;
    printf("Type something:\n");
    fgets(input,sizeof ( input ),stdin);
    if( ( p = strchr( input, '\n') ) != NULL )
    {
        *p = '\0';
    }

    printf("You typed \"%s\"\n",input);
    return 0;
}

OK,找到回车字符,将它替换成字符串结束符号,OK 。此时打印输出 为 "hehe".
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值