【进阶】3. 字符函数和字符串函数

文章说明:该文章的知识点源于B站上比特鹏哥的C语言课程,结合鹏哥上课的讲义、课堂代码以及自己的理解整理形成。

1. 函数介绍

1.1 求字符串长度

strlen

size_t strlen ( const char * str );
  1. 字符串\0 作为结束标志strlen 函数返回的是在字符串中 \0 前面出现的字符个数(计算的字符个数不包含 \0 ,但是必须有 \0,,因为 \0是结束标志 )。

  2. 参数指向的字符串必须要以 \0 结束。

  3. 注意函数的返回值为size_t,是无符号的易错)。

    int main()
    {
    	if (strlen("abc") - strlen("abcdef") > 0)
    	{
    		printf(">\n"); 
    	}
    	else
    	{
    		printf("<=\n");
    	}
    	return 0;
    }
    
    //输出结果:> 
    //想要输出正确结果需要强制类型转换一下 -> (int)(strlen("abc") - strlen("abcdef"))
    
  4. 学会 strlen 函数的模拟实现。

1.2 长度不受限制的字符串函数

直到 \0 操作才结束。

strcpy

char arr[20] = {0};
arr = "hello";//err -> 将字符h的地址放到arr数组中

因此引入 strcpy 函数。

char* strcpy(char * destination, const char * source );
  1. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
  2. 源字符串必须以 \0 结束因为要将 \0 放到目标空间去
  3. 会将源字符串中的 \0 拷贝到目标空间
  4. 目标空间必须足够大,以确保能存放源字符串。
  5. 目标空间必须可变。
  6. 学会模拟实现。
int main()
{
	char arr[20] = {0};
	strcpy(arr, "hello");//string copy -> "hello"放到表达式当中,表达的是'h'的地址
	printf("%s\n", arr);

	return 0;
}
int main()
{
	char* str = "xxxxxxxxxxxxxxxxxxx";
	char* p = "hello world";
	strcpy(str, p);//会报错,因为目标空间不可更改

	return 0;
}

strcat

char * strcat ( char * destination, const char * source );
  1. 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.
  2. 源字符串必须以 \0结束因为要将 \0 放到目标空间去
  3. 目标空间必须有足够的大,能容纳下源字符串的内容。
  4. 目标空间必须可修改。
  5. 字符串自己给自己追加,如何? -> 不能,因为 \0 被覆盖掉了,没有找到结束标志
int main()
{
	char arr1[20] = "hello ";//world
	char arr2[] = "world";
	strcat(arr1, arr2);
	printf("%s\n", arr1);

	return 0;
}

strcmp

int strcmp ( const char * str1, const char * str2 );
  1. 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.

  2. 标准规定:

    第一个字符串大于第二个字符串,则返回大于0的数字

    第一个字符串等于第二个字符串,则返回0

    第一个字符串小于第二个字符串,则返回小于0的数字

  3. 那么如何判断两个字符串? -> 字符挨个比较其ASCII值

1.3 长度受限制的字符串函数介绍

strncpy

char * strncpy ( char * destination, const char * source, size_t num );
  1. 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.
  2. 拷贝num个字符从源字符串到目标空间。
  3. 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。
int main()
{
	char arr1[20] = "abcdefghi";
	char arr2[] = "qwer";
	strncpy(arr1, arr2, 2); //相对strcpy更加安全,因为程序员要先考虑目标空间够不够
    strncpy(arr1, arr2, 6); //qwer\0\0ghi 第1个\0是字符里面的 第2个\0是strncpy函数补充的
	printf("%s\n", arr1);
	return 0;
}

strncat

char * strncat ( char * destination, const char * source, size_t num );
  1. Appends the first num characters of source to destination, plus a terminating null-character.
  2. If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.
int  main()
{
	char arr1[20] = "hello ";                
	char arr2[] = "world";
	strncat(arr1, arr2, 3);//hello wor\0
	printf("%s\n", arr1);

	return 0;
}

strncmp

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

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

int main()
{
	char* p = "aqcdef";
	char* q = "abcqwert";
	int ret = strncmp(p, q, 4);
	printf("%d\n", ret);

	return 0;
}

1.4 字符串查找

strstr

char * strstr ( const 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.

int main()
{
	char arr1[] = "abbbcdef";
	char arr2[] = "bbc";

	//在arr1中查找是否包含arr2数组
	char* ret = strstr(arr1, arr2);
	if (ret == NULL)
	{
		printf("没找到\n");
	}
	else
	{
		printf("找到了:%s\n", ret);
	}
	return 0;
}

strtok

char * strtok ( char * str, const char * sep );
  1. sep参数是个字符串,定义了用作分隔符的字符集合
  2. 第一个参数指定一个字符串,它包含了0个或者多个由sep字符串中一个或者多个分隔符分割的标记。
  3. strtok函数找到str中的下一个标记,并将其用\0结尾,返回一个指向这个标记的指针。(注:strtok函数会改变被操作的字符串,所以在使用strtok函数切分的字符串一般都是临时拷贝的内容并且可修改。)
  4. strtok函数的第一个参数不为NULL,函数将找到str中第一个标记,strtok函数将保存它在字符串中的位置。
  5. strtok函数的第一个参数为NULL,函数将在同一个字符串中被保存的位置开始,查找下一个标记。
  6. 如果字符串中不存在更多的标记,则返回NULL指针。
int main()
{
	char arr[] = "zpw@bitedu.tech hehe";
	char* p = "@. ";
	char tmp[30] = { 0 };
	strcpy(tmp, arr);
	//zpw\0bitedu\0tech\0

	char* ret = NULL;

	for (ret = strtok(tmp, p); ret != NULL; ret=strtok(NULL, p))
	{
		printf("%s\n", ret);
	}
    return 0;
}

1.5 错误信息报告

strerror

调用库函数失败的是,都会设置错误码。

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

char * strerror ( int errnum );
#include <errno.h>
#include <string.h>

int main()
{
	//printf("%s\n", strerror(0)); //No error
	//printf("%s\n", strerror(1)); //Operation not permitted
	//printf("%s\n", strerror(2)); //No such file or directory
	//printf("%s\n", strerror(3)); //No such process
	//printf("%s\n", strerror(4)); //Interrupted function call
	//printf("%s\n", strerror(5)); //Input/output error
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno)); //-> 查看错误信息
		return 1;
	}
	//...
	fclose(pf);
	pf = NULL;

	return 0;
}

strerror - 把错误码转换成错误信息 需要自行打印

perror - 1. 把错误码转换成错误信息 2. 打印错误信息(包含了自定义的信息)

1.6 字符操作

字符分类函数:

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

字符转换:

int tolower ( int c );
int toupper ( int c );
/* isupper example */
#include <stdio.h>
#include <ctype.h>

int main()
{
	char arr[20] = { 0 };
	scanf("%s", arr);
	int i = 0;
	while (arr[i] != '\0')
	{
		if (isupper(arr[i]))
		{
			arr[i] = tolower(arr[i]);
		}
		printf("%c ", arr[i]);
		i++;
	}

	return 0;
}

1.7 内存操作函数

memcpy - 内存拷贝

void * memcpy ( void * destination, const void * source, size_t num );
  1. 函数memcpy从source的位置开始向后复制num个字节的数据到destination的内存位置。
  2. 这个函数在遇到 \0 的时候并不会停下来。
  3. 如果source和destination有任何的重叠,复制的结果都是未定义的
int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int arr2[20] = { 0 };
	memcpy(arr2, arr1, 20);
	return 0;
}

memcpy - 只要实现了不重叠拷贝就可以了,而VS中的实现既可以拷贝不重叠,也可以拷贝重叠内存

memmove - 内存移动

void * memmove ( void * destination, const void * source, size_t num );
  1. memmove和memcpy的差别就是memmove函数处理的源内存块和目标内存块是可以重叠的。
  2. 如果源空间和目标空间出现重叠,就得使用memmove函数处理
int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
	memmove(arr1+2, arr1, 20);
	return 0;
}

memcmp - 内存比较

int memcmp ( const void * ptr1, 
             const void * ptr2, 
             size_t num );

比较从ptr1和ptr2指针开始的num个字节

memcmp - 内存比较

int main()
{
	float arr1[] = { 1.0, 2.0,3.0,4.0 };
	float arr2[] = { 1.0, 3.0 };
	int ret = memcmp(arr1, arr2, 8);
	printf("%d\n", ret);

	return 0;
}

memset - 内存设置

将指定内存的前num字节的内容设置成value

void * memset ( void * ptr, int value, size_t num );
int main()
{
	int arr[8] = { 0 }; //32个字节
	memset(arr, 1, 20);  //以字节为单位设置内存的
	//01010101 01010101 01010101 01010101 01010101 00000000 00000000 00000000
	return 0;
}

2. 库函数的模拟实现

2.1 求字符串长度

my_strlen

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

int my_strlen(const char* str)
{
	int count = 0;//计数器
	assert(str != NULL);

	while (*str != '\0')
	{
		count++;
		str++;
	}
	return count;
}

int main()
{
	char arr[] = "abc";
    //char arr[] = { 'a', 'b', 'c' };
	int len  = my_strlen(arr);
	printf("%d\n", len);

	return 0;
}

一共有3种方式:

方式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;
}

2.2 长度不受限制的字符串函数

my_strcpy

char *my_strcpy(char *dest, const char*src)
{   
    char *ret = dest;
    assert(dest != NULL);
    assert(src != NULL);
    
    while((*dest++ = *src++))
    {
        ;
    }
    return ret;
}

my_strcat

char* my_strcat(char* dest, const char*src)
{
	char* ret = dest;
	assert(dest && src);
	//1. 找目标字符串中的\0
	while (*dest)
	{
		dest++;
	}
	//2. 追加源字符串,包含\0
	while(*dest++ = *src++)
	{
		;
	}

	return ret;//返回的目标空间的起始地址
}

int main()
{
	char arr1[20] = "hello ";//world
	char arr2[] = "world";
	//my_strcat(arr1, arr2);//字符串追加(连接)
	printf("%s\n", my_strcat(arr1, arr2));

	return 0;
}

my_strcmp

int my_strcmp(const char* s1, const char* s2)
{
	assert(s1 && s2);
	while (*s1 == *s2)
	{
		if (*s1 == '\0')
		{
			return 0;
		}
		s1++;
		s2++;
	}
	if (*s1 > *s2)
	{
		return 1;
	}
	else
	{
		return -1;
	}
}


int my_strcmp(const char* s1, const char* s2)
{
	assert(s1 && s2);
	while (*s1 == *s2)
	{
		if (*s1 == '\0')
		{
			return 0;
		}
		s1++;
		s2++;
	}
	return *s1 - *s2;
}

int main()
{
	char* p = "abcdef";
	char* q = "abcdef";
	int ret = my_strcmp(p, q);

	if (ret > 0)
	{
		printf("p > q\n");
	}
	else if (ret < 0)
	{
		printf("p < q\n");
	}
	else
	{
		printf("p == q\n");
	}

	return 0;
}

2.3 字符串查找

my_strstr

char* my_strstr(const char* str1, const char* str2) //自行研究KMP字符串查找算法
{
	assert(str1 && str2);
	const char* s1 = NULL;
	const char* s2 = NULL;
	const char* cp = str1;

	if (*str2 == '\0')
	{
		return (char*)str1;
	}

	while (*cp)
	{
		s1 = cp;
		s2 = str2;
		while (*s1 && *s2 && (*s1 == *s2))
		{
			s1++;
			s2++;
		}
		if (*s2 == '\0')
		{
			return (char*)cp;
		}
		cp++;
	}

	return NULL;
}

int main()
{
	char arr1[] = "abbbcdef";
	char arr2[] = "bbc";

	//在arr1中查找是否包含arr2数组
	char* ret = my_strstr(arr1, arr2);
	if (ret == NULL)
	{
		printf("没找到\n");
	}
	else
	{
		printf("找到了:%s\n", ret);
	}
	return 0;
}

2.7 内存操作函数

my_memcpy

#include <assert.h>

void* my_memcpy(void* dest, const void* src, size_t num)
{
	void* ret = dest;
	assert(dest && src);

	while (num--)//4 3 2 1
	{
		*(char*)dest = *(char*)src;
		dest = (char*)dest + 1;
		src = (char*)src + 1;
	}
	return ret;
}

int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int arr2[20] = { 0 };
	my_memcpy(arr2, arr1, 20);
	return 0;
}

my_memove

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--)//19
		{
			*((char*)dest + num) = *((char*)src + num);
		}
	}
	return ret;
}

int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
	my_memmove(arr1+2, arr1, 20);
    //my_memmove(arr1, arr1+2, 20);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值