字符串+内存函数-C语言进阶

本章重点

介绍 处理字符和字符串的库函数 的使用和注意事项

  • 求字符串长度
    • strlen
  • 长度不受限制的字符串函数
    • strcpy
    • strcat
    • strcmp
  • 长度不受限制的字符串函数
    • strncpy
    • strncat
    • strncmp
  • 字符串查找
    • strstr
    • strtok
  • 错误信息报告
    • strerror
  • 字符操作
  • 内存操作函数
    • memcpy
    • memmove
    • memset
    • memcmp

0. 前言

C 语言中对字符和字符串的处理很频繁,但是 C 语言本身是没有字符串类型的,字符串通常放在 常量字符串 中或者 字符数组 中。
字符串常量 适用于那些对它不做修改的字符串函数。

1. 函数介绍

1.1 strlen

size_t strlen ( const char * str );

  • 字符串以 ‘\0’ 作为结束标志,strlen 函数返回的是在字符串中 ‘\0’ 前面出现的字符个数(不包括 ‘\0’)。
  • 参数指向的字符串必须要以 ‘\0’ 结尾。
  • 注意函数的返回值是 size_t,是无符号的整型(易错)
  • 学会 strlen 函数的模拟实现
    #include <stdio.h>
    #include <string.h>
    #include <assert.h>
    
    //计数器方法
    //指针 - 指针
    //递归方法
    size_t my_strlen(const char* str) {
        assert(str);
        int count = 0;
        while (*str != '\0') {
     	   count++;
     	   str++;
        }
        return count;
    }
    

易错代码:

#include <stdio.h>
#include <string.h>

int main() {
	const char* str1 = "abcdef";
	const char* str2 = "bbb";
	if (strlen(str2) - strlen(str1) > 0) {
		printf("strlen(str2) > strlen(str1)\n");
	}
	else {
		printf("strlen(str2) < strlen(str1)\n");
	}
	return 0;
}

1.2 strcpy

char * strcpy ( char * destination, const char * source );

  • Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
  • 源字符串必须以 ‘\0’ 结束
  • 会将源字符串中的 ‘\0’ 拷贝到目标空间
  • 目标空间必须足够大,以确保能存放源字符串。(不够会导致崩溃)
  • 目标空间必须可修改。
    char* p = "abc"; char arr[] = "def"; strcpy(p, arr);(崩溃)
  • 学会模拟实现。
char* my_strcpy(char* destination, const char* source) {
    assert(source && destination);
	char* tmp = destination;
 	while (*destination++ = *source++) {
    	;
	}
	return tmp;
}

1.3 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’ 结束
  • 会将源字符串中的 ‘\0’ 拷贝到目标空间
  • 目标空间必须足够大,以确保能容纳下源字符串的内容。(不够会导致崩溃)
  • 目标空间必须可修改。
  • 字符串自己给自己追加,如何?

    不能,源字符串的首字母会覆盖源字符串的 ‘\0’,代码陷入死循环。

char* my_strcpy(char* destination, const char* source) {
    assert(source && destination);
	char* tmp = destination;
	//1.找到目标空间的末尾'\0'
	while (*detination != '\0') {
		detination++;
	}
	//2.拷贝字符串
 	while (*destination++ = *source++) {
    	;
	}
	return tmp;
}

1.4 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 的数字
    • 那如何判断两个字符串?( ‘\0’ 也参与到字符串的比较当中)
char* my_strcmp(const char* str1, const char* str2) {
    assert(str1 && str2);
    while(*str1 == *str2) {
    	if (*str1 == '\0')
    		return 0;
    	str1++;
    	str2++;
    }
    return *str1 - *str2;
}

1.5 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 个。

1.6 strncat

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.
  • 追加 num 个字符从源字符串到目标空间。
  • 如果 num 小于等于源字符串的长度,则拷贝完源字符串之后,在目标的后边追加一个 ‘\0’;如果 num 大于源字符串的长度,则拷贝完源字符串的 ‘\0’ 之后结束,不继续追加 ‘\0’。

1.7 strncmp

int strncmp ( const char * str1, const char * str2, size_t num );

  • 比较到出现另一个字符不一样 或者 一个字符串结束 或者 num个字符全部比较完。

1.8 strstr

const char * strstr ( const char * str1, const char * str2 );
char * strstr ( char * str1, const char * str2 );

  • Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
  • 查找子串:str1 中是否出现 str2 这个子串。如果找到了,返回子串在 str1 中所在的第一个字符的位置;如果找不到,返回 NULL。
  • 模拟实现
char* my_strstr(const char* str1, const char* str2) {
    assert(str1 && str2);
    const char* s1 = str1;
    const char* s2 = str2;
    const char* p = str1;
    while (*p) {
    	s1 = p;
    	s2 = str2;
    	while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2) {
    		s1++;
    		s2++;
    	}
    	if (*s2 == '\0') {
    		return (char*)p;
    	}
    	p++;
    }
    return NULL;
}
#include <stdio.h>
#include <string.h>

int main() {
	char arr1[] = "abbbcdef";
	char arr2[] = "bbc";
	char* ret = strstr(arr1, arr2);

	if (ret == NULL) {
		printf("子串不存在\n");
	} 
	else {
		printf("%s\n", ret);
	}

	return 0;
}

1.9 strtok

char * strtok ( char * str, const char * delimiters );

  • delimiters 参数是个字符串,定义了用于分隔符的字符集合。
  • 第一个参数指定一个字符串,它包含了 0 个或者多个由 delimiters 字符串中的一个或者多个分隔符分割的标记。
  • strtok 函数找到 str 中的下一个标记,并将其用 ‘\0’ 结尾,返回一个指向这个标记的指针。(注:strtok 函数会改变被操作的字符串,所以在使用 strtok 函数切分的字符串一般都是临时拷贝的内容并且可以修改。)
  • strtok 函数的第一个参数不为 NULL,函数将找到 str 中第一个标记,strtok 函数将保存它在字符串中的位置。
  • strtok 函数的第一个参数为 NULL,函数将在同一个字符串被保存的位置开始,查找下一个标记。
  • 如果字符串中不存在更多的标记,则返回 NULL 指针。
#include <stdio.h>
#include <string.h>

int main() {
	const char* seq = "@.";//标记:{'@', '.', '\0'};
	char email[] = "zhangsan@163.com";
	char cmp[30] = { 0 };
	strcpy(cmp, email);

	char* ret = NULL;
	for (ret = strtok(cmp, seq); ret != NULL; ret = strtok(NULL, seq)) {
		printf("%s\n", ret);
	}

	return 0;
}

1.10 strerror

char * strerror ( int errnum );

返回错误码所对应的错误信息。

  • C语言的库函数,在执行失败的时候,都会设置错误码(error)。
  • error: C语言设置的一个全局的错误码存放的变量。(存放在 errno.h 头文件中)
#include <errno.h>

FILE* pf = fopen("test.txt", "r");
if (pf == NULL) {
	printf("Error opening file unexist.ent: %s\n", strerror(error));
	return 1;
}

1.11 字符分类函数(在头文件 ctype.h 中)

函数如果它的参数符合下面条件就返回真真时 返回值
iscntrl任何控制字符
isspace空白字符:空格 ’ ',换页 ‘\f’,换行 ‘\n’,回车 ‘\r’,制表符 ‘\t’ 或者垂直制表符 ‘\v’8
isdigit十进制数字 0~94
isxdigit十六进制数字,包括所有十进制数字,小写字母 a~f,大写字母 A~F128
islower小写字母 a~z2
isupper大写字母 A~Z1
isalpha字母 a~z 或 A~Z1/2
isalnum字母或者数字,a~z,A~Z,0~91/2/4
ispunct标点符号,任何不属于数字或者字母的图形符号(可打印)
isgraph任何图形符号
isprint任何可打印字符,包括图像字符和空白字符

1.12 字符转换

可以将字符进行大小写转换。其他字符不做改变。

int tolower (int c);
int toupper (int c);

2. 内存函数

2.1 memcpy

内存拷贝(memory copy):
void * memcpy ( void * destination, const void * source, size_t num );

  • Copies the values of num bytes from the location pointed to by source directly to the memory block pointed to by destination.
  • 函数 memcpy 从 source 的位置开始往后复制 num 个字节的数据到 destination 的内存位置。
  • 这个函数在遇到 ‘\0’ 的时候并不会停下来。
  • memcpy 函数负责拷贝两块独立空间中的数据,如果 source 和 destination 有任何的重叠,拷贝的结果都是未定义的。
  • 模拟实现
void* my_memcpy(void* dest, const void* src, size_t num) {
    assert(dest && src);
    void* ret = dest;
    while (num--) {
    	*(char*)dest = *(char*)src;
    	dest = (char*)dest + 1;
    	src= (char*)src+ 1;
    }
    return ret;
}

dest = (char*)dest + 1; 为什么不能写成 (char*)dest++;
强制类型转换后得到的对象是临时对象,在临时对象上 ++ 没有意义。

2.2 memmove

内存拷贝(memory move):
void * memmove ( void * destination, const void * source, size_t num );

  • Copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.
  • 和 memcpy 的差别就是 memmove 函数可以实现重叠内存之间的数据拷贝。
  • 如果源空间和目标空间出现重叠,就得使用 memmove 函数处理。
  • 模拟实现
void* my_memmove(void* dest, const void* src, size_t num) {
    assert(dest && src);
    void* ret = dest;
    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;
}

2.3 memcmp

内存比较(memory compare):
int memcmp ( const void * ptr1, const void * ptr2, size_t num );

  • Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not.
  • 比较从 ptr1 和 ptr2 指针开始的 num 个字节。
  • 标准规定:
    • 第一个指针指向的字节大于第二个指针指向的字节,则返回大于 0 的数字
    • 第一个指针指向的字节等于第二个指针指向的字节,则返回 0
    • 第一个指针指向的字节小于第二个指针指向的字节,则返回小于 0 的数字

2.4 memset

内存设置(memory set):
void * memset ( void * ptr, int value, size_t num );

  • Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
  • 从 ptr 指向的字节开始往后的 num 个字节都设置为 value。
char arr[] = "hello abc";

memset(arr, 'x', 5);
//xxxxx abc
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值