本章重点介绍处理字符和字符串的库函数的使用和注意事项
C语言中对字符和字符串的处理很是频繁,
但是C语言本身是没有字符串类型的,字符串通常放在常量字符串或者字符数组中。
字符串常量 适用于那些对它不做修改的字符串函数.
目录
一.strlen函数:获取字符串长度
size_t strlen ( const char * str );
字符串以 '\0' 作为结束标志,strlen函数返回的是在字符串中 '\0' 前面出现的字符个数
注:
- 参数指向的字符串必须要以 '\0' 结束。
- 注意函数的返回值为size_t,是无符号的( 易错 )
例题.
#include <stdio.h>
int main()
{
const char*str1 = "abcdef";
const char*str2 = "bbb";
if(strlen(str2)-strlen(str1)>0)
{
printf("str2>str1\n");
}
else
{
printf("srt1<str2\n");
}
return 0;
}
由于strlen函数的返回值是size_t 是无符号整型
两无符号整型相减,得到的也是无符号整型
所以这里打印的结果是 str2>str1
三种方式模拟实现strlen函数
方式1:
//计数器方式
int my_strlen(const char * str)
{
int count = 0;
while(*str)
{
count++;
str++;
}
return count;
}
方式2:
//不创建临时变量计数器,用递归
int my_strlen(const char * str)
{
if(*str == '\0')
return 0;
else
return 1+my_strlen(str+1);
}
方式3:
//指针-指针的方式
int my_strlen(char *s)
{
char *p = s;
while(*p != ‘\0’ )
p++;
return p-s;
}
二.长度不受限制的字符串函数
strcpy函数:字符串的拷贝
char* strcpy(char * destination, const char * source );
Copies the C string pointed by source into the array pointed by destination, including theterminating null character (and stopping at that point).
- 源字符串必须以 '\0' 结束。
- 会将源字符串中的 '\0' 拷贝到目标空间。
- 目标空间必须足够大,以确保能存放源字符串。
- 目标空间必须可变
模拟实现
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dest, const char* src)
{
assert(dest && src);//断言
char* ret = dest;
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = "xxxxxxxxxxxxx";
char arr2[] = "hello";
my_strcpy(arr1, arr2);
printf("%s", arr1);
printf("%s\n",my_strcpy(arr1, arr2));
return 0;
}
strcat函数:字符串连接
char * strcat ( char * destination, const char * source );
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.
- 源字符串必须以 '\0' 结束。
- 目标空间必须有足够的大,能容纳下源字符串的内容。
- 目标空间必须可修改。
模拟实现
char* my_strcat(char* dest, const char* src)
{
assert(dest&&src);
int i = 0;
while (*(dest + i) != '\0')
{
i++;
}
while (*src != '\0')
{
*(dest + i++) = *src++;
}
*(dest + i) = '\0';
return dest;
}
strcmp函数:字符串比较
int strcmp ( const char * str1, const char * str2 );
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
标准规定:
- 第一个字符串大于第二个字符串,则返回大于0的数字
- 第一个字符串等于第二个字符串,则返回0
- 第一个字符串小于第二个字符串,则返回小于0的数字
int my_strcmp (const char * src, const char * dst)
{
int ret = 0 ;
assert(src != NULL);
assert(dest != NULL);
while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst)
++src, ++dst;
if ( ret < 0 )
ret = -1 ;
else if ( ret > 0 )
ret = 1 ;
return( ret );
}
三.长度受限制的字符串函数介绍
strncpy函数
char * strncpy ( char * destination, const char * source, size_t num );
Copies the first num characters of source to destination. If the end of the source C string(which is signaled by a null-character) is found before num characters have been copied,destination is padded with zeros until a total of num characters have been written to it.
- 拷贝num个字符从源字符串到目标空间。
- 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[] = "xxxxxxxxxxxxxxxx";
char arr2[] = "hello world";
strncpy(arr1, arr2, 5);
printf("%s\n", arr1); //helloxxxxxxxxxxx
}
如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个
int main()
{
char arr1[] = "xxxxxxxxxxxxxxxx";
char arr2[] = "he";
strncpy(arr1, arr2, 5);
printf("%s\n", arr1); //he\0\0\0 ->he
}
模拟实现
#include<stdio.h>
#include<assert.h>
char* my_strncpy(char* dest, const char* str, size_t n)
{
assert(dest && str);
char* ret = dest;
while (n--)
{
*dest++ = *str++;
}
return ret;
}
int main()
{
char arr1[] = "xxxxxxxxxx";
char arr2[] = "abcde";
printf("%s\n", my_strncpy(arr1, arr2, 4)); // abcdxxxxxx
return 0;
}
strncat函数
- 功能:连接指定元素个数的字符串函数
- strncat从目标字符串从左向右数到第一个 '\0' 的位置开始连接源指定字符串
char * strncat ( char * destination, const char * source, size_t num );
Appends the first num characters of source to destination, plus a terminating null-character.
If the length of the C string in source is less than num, only the content up to the terminating null-character is copied
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20];
char str2[20];
strcpy(str1, "To be ");
strcpy(str2, "or not to be");
strncat(str1, str2, 6);
puts(str1);
return 0;
}
- 注意:
strncat追加后,会主动在追加后放一个 '\0' 进去,确保其是个字符串。
模拟实现
#include<stdio.h>
#include<assert.h>
char* my_strncat(char* dest, const char* str, size_t n)
{
assert(dest && str);
char* ret = dest;
while (*dest)
{
dest++;
}
while (n--)
{
*dest++ = *str++;
}
*dest = '\0';
return ret;
}
int main()
{
char arr1[20] = "hello\0xxxxx";
char arr2[] = "worldxxxxx";
printf("%s\n", my_strncat(arr1, arr2, 5)); //helloworld
return 0;
}
strncmp函数
int strncmp ( const char * str1, const char * str2, size_t num );
比较到出现两个字符不一样或者一个字符串结束或者num个字符全部比较完
- 功能:实现指定位置的字符数比较函数
#include <stdio.h>
#include <string.h>
int main()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts("Looking for R2 astromech droids...");
for (n = 0; n < 3; n++)
if (strncmp(str[n], "R2xx", 2) == 0)
{
printf("found %s\n", str[n]);
}
return 0;
}
模拟实现
#include<stdio.h>
#include<assert.h>
int my_strncmp(char* dest, const char* str, size_t n)
{
int ret = 0;
assert(dest && str);
while (n && !(*dest - *str))
{
n--;
dest++;
str++;
}
if (n && *dest - *str > 0)
return 1;
else if (n && *dest - *str < 0)
return -1;
return ret;
}
int main()
{
char arr1[] = "abcdef";
char arr2[] = "abcqqqqq";
printf("%d\n", my_strncmp(arr1, arr2, 3));
return 0;
}
四.字符串查找函数
strstr函数
功能:判断一个字符串是否为另一字符串的子集,若是,返回从第一个相等处的地址
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of
str1.
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[] = "abbbcdef";
char arr2[] = "bbc";
char* ret = strstr(arr1, arr2);
if (NULL == ret)
printf("没找到\n");
else
printf("%s\n", ret); // bbcdef
return 0;
}
模拟实现
#include<stdio.h>
#include<assert.h>
char* my_strstr(const char* str, const char* substr)
{
const char* s1 = str;
const char* s2 = substr;
const char* cur = str;
assert(str && substr);
if (*substr == '\0')
{
return (char*)str;
}
while (*cur)
{
s1 = cur;
s2 = substr;
while (*s1 && *s2 && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
return (char*)cur;
cur++;
}
return NULL;
}
int main()
{
char arr1[] = "abbbcdef";
char arr2[] = "bbc";
char* ret = my_strstr(arr1, arr2);
if (NULL == ret)
printf("没找到\n");
else
printf("%s\n", ret);//bbcdef
return 0;
}
strtok函数
- 功能:把一串字符串按照分隔符来切割
注意:
char * strtok ( char * str, const char * sep );
- sep参数是个字符串,定义了用作分隔符的字符集合。
- 第一个参数指定一个字符串,它包含了0个或者多个由sep字符串中一个或者多个分隔符分割的标记。
- strtok函数找到str中的下一个标记,并将其用 \0 结尾,返回一个指向这个标记的指针。(注:strtok函数会改变被操作的字符串,所以在使用strtok函数切分的字符串一般都是临时拷贝的内容并且可修改。)
- strtok函数的第一个参数不为 NULL ,函数将找到str中第一个标记,strtok函数将保存它在字符串中的位置。
- strtok函数的第一个参数为 NULL ,函数将在同一个字符串中被保存的位置开始,查找下一个标记。
- 如果字符串中不存在更多的标记,则返回 NULL 指针
#include <string.h>
int main()
{
const char* p = "@.#,";
char arr[] = "zhangsan@qq.com";
char buf[50] = { 0 };// "zhangsan@qq.com";
strcpy(buf, arr);
char* str = strtok(buf, p);
printf("%s\n", str);//zhangsan
str = strtok(NULL, p);
printf("%s\n", str);//qq
str = strtok(NULL, p);
printf("%s\n", str);//com
str = strtok(NULL, p);
printf("%s\n", str);
//strtok - 开始返回NULL
return 0;
}
五.错误信息报告
strerror函数
- 功能:把错误码翻译成错误信息
- C语言中,规定了一些信息,错误码 - 错误信息
#include<stdio.h>
#include<string.h>
int main()
{
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d = %s\n", i, strerror(i));
}
return 0;
}
用途示例:
C语言可以操作文件,打开文件 - fopen
当库函数使用的时候,发生错误会把errno这个全局的错误变量设置为本次执行库函数产生的错误码,errno是C语言提供的一个全局变量,可以直接使用,是在errno.h文件中的
#include<stdio.h>
#include <errno.h>
#include<string.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (NULL == pf)
{
//出错误的原因是什么
printf("%s\n", strerror(errno)); //No such file or directory
return 0;
}
//读文件
//...
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
六.字符操作
1.字符分类函数
例如:isdigit
char ch = '0';
if (ch >= '0' && ch <= '9')
{
//复杂
}
if (isdigit(ch))
{
//方便快捷
}
2.字符转换函数
int tolower ( int c ); //把大写转为小写
int toupper ( int c ); //把小写转为大写
#include<stdio.h>
#include <ctype.h>
int main()
{
char ch = 0;
while (ch = getchar())
{
if (islower(ch))
{
ch = toupper(ch);
}
else
{
ch = tolower(ch);
}
printf("%c", ch);
}
return 0;
}
七.内存操作函数
memcpy函数
void * memcpy ( void * destination, const void * source, size_t num );
功能:可拷贝不同类型的数据
#include<stdio.h>
#include<string.h>
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[5] = { 0 };
memcpy(arr2, arr1, 5 * sizeof(arr1[0]));
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", arr2[i]); // 1 2 3 4 5
}
return 0;
}
注意:
- 函数memcpy从source的位置开始向后复制num个字节的数据到destination的内存位置。
- 这个函数在遇到 '\0' 的时候并不会停下来。
- 如果source和destination有任何的重叠,复制的结果都是未定义的。
模拟实现
#include<stdio.h>
#include <assert.h>
void* my_memcpy(void* dest, const void*src, size_t num)
{
void* ret = dest;
assert(dest && src);
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr3[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr4[5] = { 0 };
my_memcpy(arr4, arr3+5, 5*sizeof(arr3[0]));
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", arr4[i]); //6 7 8 9 10
}
return 0;
}
- C语言只要求:
- memcpy能拷贝不重叠的内存空间就可以了
- memmove去处理那些重叠拷贝
memmove函数
功能:同样可拷贝不同类型的数据,不过可以重叠
#include<stdio.h>
#include<string.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
memmove(arr + 2, arr, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]); //1 2 1 2 3 4 5 8 9 10
}
return 0;
}
注意
- 和memcpy的差别就是memmove函数处理的源内存块和目标内存块是可以重叠的。
- 如果源空间和目标空间出现重叠,就得使用memmove函数处理。
模拟实现
#include<stdio.h>
#include <assert.h>
void* my_memmove(void* dest, const void* src, size_t num)
{
void* ret = dest;
assert(dest && src);
if (dest < src)
{
//前->后
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
//后->前
while (num--)
{
*((char*)dest+num) = *((char*)src + num);
}
}
return ret;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
my_memmove(arr + 2, arr, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]); //1 2 1 2 3 4 5 8 9 10
}
return 0;
}
memset函数
功能:把一块内存空间设置成你想要的值,以字节为单位来修改
#include<stdio.h>
#include<string.h>
int main()
{
//char arr[20] = { 0 };
//memset(arr, 'x', 10);
//printf("%s\n", arr); //xxxxxxxxxx
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
memset(arr, '\0', 10);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]); // 0 0 0 4 5 6 7 8 9 10
}
//01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 ...将前10个字节改为0
//00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00
return 0;
}
memcmp函数
功能:内存比较
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
比较从ptr1和ptr2指针开始的num个字节,不在乎有无 '\0' ,你让它比较几个字节就比较几个字节
#include<stdio.h>
#include<string.h>
int main()
{
int arr1[] = { 1,2,7,4,5 };
int arr2[] = { 1,2,3,4,5 };
printf("%d\n", memcmp(arr1, arr2, 9)); //1 // 9表示比较前9个字节
return 0;
}