本文主要是介绍c语言 strstr,strok,strerror,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
上述三个函数均是用在字符串应用中的,以及头文件都为#include<string.h>
strstr
用处:
用来进行字符串查找的函数,比如有两个字符串str1和str2,返回指向 str1 中 str2 第一次出现的指针,如果 str2 不是 str1 的一部分,则返回 null 指针。
格式:
strstr(str1,str2);
例子:
上述格式中的意思就是在str1中有没有str2这个字符串
代码:
#include <stdio.h>
#include <string.h>int main ()
{char str[] ="This is a simple string";char * pch;pch = strstr (str,"simple");if (pch != NULL)strncpy (pch,"sample",6);puts (str);return 0;
}
//This is a sample string
strok
用处:
对一个字符串进行分段输出的,此函数的一系列调用将 str 拆分为标记,标记是由分隔符中的任何字符分隔的连续字符序列。
格式:
strtok(arr,p);
例子:
比如arr里面有“123,5674.245.”而p里有“…”,那输出结果就应该为分别为123和5674和245
代码:
#include <stdio.h>
#include <string.h>int main ()
{char str[] ="- This, a sample string.";char * pch;printf ("Splitting string \"%s\" into tokens:\n",str);pch = strtok (str," ,.-");while (pch != NULL){printf ("%s\n",pch);pch = strtok (NULL, " ,.-");}return 0;
}
//输出结果为Splitting string "- This, a sample string." into tokens:
//This
//a
//sample
//string
strerror
用处:
获取指向错误消息字符串的指针
格式:
strerror(errno)
例子:
让字符串被strerror后如果没报错则没反应,报错后将暑促错误原因
代码:
#include <stdio.h>
#include <string.h>
#include <errno.h>int main ()
{FILE * pFile;pFile = fopen ("unexist.ent","r");if (pFile == NULL)printf ("Error opening file unexist.ent: %s\n",strerror(errno));return 0;
}
//输出结果Error opening file unexist.ent: No such file or directory
这篇关于c语言 strstr,strok,strerror的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!