1.1 strstr - Locate substring (在字符串里定位子字符串)
const char * strstr ( const char * str1, const char * str2 ); char * strstr ( char * str1, const char * str2 );
str1
C string to be scanned.
str2
C string containing the sequence of characters to match.
即寻找str2在str1里第一次出现的位置;
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
The matching process does not include the terminating null-characters, but it stops there.
找到了就返回第一次出现位置的地址,找不到就返回空指针(NULL);
A pointer to the first occurrence in str1 of the entire sequence of characters specified in str2, or a null pointer if the sequence is not present in str1.
strstr 的模拟实现
const char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
char* cp = (char*)str1;//保持str1和str2不变;
char* s1; char* s2;
if (str2 == NULL)//if (!*str2)//如果arr2为空指针,就直接返回str1;
return (char*)str1;
while (*cp)
{
s1 = cp;
s2 = (char*)str2;
while (*s1 && *s2 && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return cp;
}
cp++;
}
return (NULL);
}
int main()
{
char arr1[] = "to be or not to be";
char arr2[] = "be";
printf("%s", my_strstr(arr1, arr2));
return 0;
}
1.2 strtok - Split string into tokens
char * strtok ( char * str, const char * delimiters );
> str 是一个指定的字符串,包含0个或多个第二个参数里面的分隔符标记;
> delimiters (参数是个字符串,定义了分隔符的字符集合;)C string containing the delimiter characters. These can be different from one call to another.
strtok函数找到str中的下一个标记,并将其用\0结尾,返回一个指向这个标记的指针。找到一个标记的时候,strtok函数将保存它在字符串中的位置,然后开始下一个标记的查找;如果字符串中不存在更多的标记,则返回NULL指针;
int main()
{
char* p = "today @is a *fairy# tale";
const char* del = "@*#";
char arr[30];
char* str = NULL;
strcpy(arr, p);//将源数据拷贝一份;
for (str = strtok(arr, del); str != NULL; str = strtok(NULL, del))//开始传非空指针,因为位置会被保留,所以后面传空指针就行;
{
printf("%s\n", str);
}
return 0;
}
注意:strtok函数会改变被操作的字符串,所以在使用strtok的时候要临时拷贝一份源字符串,并用拷贝的字符串进行操作;
1.3 strerror - Get pointer to error message string
char * strerror ( int errnum );
Interprets the value of errnum, generating a string with a message that describes the error condition as if set to errno by a function of the library.
库函数在执行的时候,会发生错误,会将一个错误码存放在errno这个变量中;
The returned pointer points to a statically allocated string, which shall not be modified by the program. Further calls to this function may overwrite its content (particular library implementations are not required to avoid data races).
errno是C语言提供的一个全局变量,后面一旦产生新的错误就会覆盖之前的错误码,所以要即使检查;
The error strings produced by strerror may be specific to each system and library implementation.
/* strerror example : error list */
#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;
}