1.strchr
函数原型:extern char *strchr(const char *s,char c)
头文件:#include <string.h>
功能:查找字符串s中首次出现字符c的位置
上篇文章我们需要处理分隔一些命令来传递给一个指针数组,正好用到这个函数,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".