字符串处理函数
- 格式:doc
- 大小:60.00 KB
- 文档页数:9
字符串处理函数(string.h)
strcat strchr strrchr strcmp strcpy strlen
strstr strpbrk strcspn strrev strnset strset
strtok strupr strlwr memccpy memchr memicmp memmove
strcat
原型: char *strcat(char *str1, char *str2);
功能: 字符串连接函数,把字符串 str2 接到 str1 后面,str1 后面的'\0 '被取消。程序示例:
#include
#include
int main( void )
{
char string[80];
strcpy( string, "Hello world from " );
strcat( string, "strcpy " );
strcat( string, "and " );
strcat( string, "strcat!" );
printf( "String = %s\n", string );
return(0);
}
输出结果:String = Hello world from strcpy and strcat!
strchr
原型: char *strchr(char *str, char c);
功能:找出 str 指向的字符串中第一次出现字符 ch 的位置指针。程序示例:
#include
#include
int main(void)
{
char string[15];
char *ptr, c = 'r';
strcpy(string, "This is a string");
ptr = strchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr-string);
else
printf("The character was not found\n");
return(0);
}
输出结果:The character r is at position: 12
strrchr
原型: char *strrchr(const char *s, int c)
功能: 得到字符串 s 中最后一次出现字符 ch 的位置指针。程序示例:
#include
#include
int main(void)
{
char string[15];
char *ptr,c='r';
strcpy(string,"This is a string");
ptr=strrchr(string,c);
if (ptr)
printf("The character %c is at position:%d",c,ptr-string);
else
printf("The character was not found");
return(0);
}
输出结果:The character r is at position:12
strcmp
原型: int strcmp(char *str1, char *str2);
功能: 比较两个字符串 str1、str2,当 s1 小于 s2 时,返回值小于 0;当 s1 等于s2 时,返回值等于 0;当 s1 大于 s2 时,返回值大于 0。程序示例:
#include
#include
int main(void)
{
char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc";
int ptr;
ptr = strcmp(buf2, buf1);
if (ptr> 0)
printf("buffer 2 is greater than buffer 1\n");
else
printf("buffer 2 is less than buffer 1\n");
ptr = strcmp(buf2, buf3);
if (ptr> 0)
printf("buffer 2 is greater than buffer 3\n");
else
printf("buffer 2 is less than buffer 3\n");
return(0);
}
输出结果:
buffer 2 is greater than buffer 1
buffer 2 is less than buffer 3
strcpy
原型: char *strcpy(char *str1, char *str2);
功能: 把 str2 指向的字符串拷贝到 str1 中。程序示例:
#include
#include
int main(void)
{
char str1[10];
char *str2 = "abcdefghi";
strcpy(str1, str2);
printf("%s\n", str1);
return(0);
}
输出结果:abcdefghi
strlen
原型: unsigned int strlen(char *str);
功能: 统计字符串中字符的个数 (不包含'\0')。程序示例:
#include
#include
int main( void )
{
char buffer[61] = "How long am I?";
int len;
len = strlen( buffer );
printf( "%s is %d characters long\n", buffer, len );
return(0);
}
输出结果:How long am I? is 14 characters long
strstr
原型: char *strstr(char *str1, char *str2);
功能: 从字符串 str1 中查找是否有字符串 str2,如果有,从 str1 中的 str2 位置起,返回 str1 中 str2 起始位置的指针,如果没有,返回 NULL。程序示例:
#include
#include
int main(void)
{
char *str1 = "Borland International", *str2 = "nation", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %s\n", ptr);
return(0);
}
输出结果:The substring is: national
strpbrk
原型: char *strpbrk(const char *s1, const char *s2);
功能: 依次检验字符串 s1 中的字符,当被检验字符在字符串 s2 中也包含时,则停止检验,并返回该字符位置,空字符 NULL 不包括在内。程序示例:
#include
#include
int main(void)