字符串匹配:
原型:char* strstr(char *str1, char *str2);
//str1 为最初的长字符串,str2 为需要匹配的短字符串。成功时,返回第一次匹配到时的片段首地址;失败时,返回 NULL。
/* strstr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a simple string";
char * pch;
pch = strstr (str,"simple");
strncpy (pch,"sample",5);
puts (str);
return 0;
}
This is a sample string
字符匹配:
原型:char* strstr(char *str, int character);
//str 为最初的长字符串,character 为需要匹配的单个字符。成功时,返回第一次匹配到时的字符在字符串中的地址;失败时,返回 NULL。
/* strchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
<pre name="code" class="cpp">Looking for the 's' character in "This is a sample string"...
found at 4
found at 7
found at 11
found at 18