03.字符函数和字符串函数

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

1. 函数介绍
1.1 strlen

size_t strlen ( const char * str );

✳字符串以 '\0' 作为结束标志,strlen函数返回的是在字符串中 '\0' 前面出现的字符个数(不包
含 '\0' )。

✳参数指向的字符串必须要以 '\0' 结束。('\0'表示字符串结束,它在ASCII中的值为0(数值0,非字符‘0’))
✳注意函数的返回值为size_t,是无符号的( 易错 )
✳学会strlen函数的模拟实现

//strlen函数模拟
#include <assert.h>

递归
int my_strlen1(const char* str)
{
	assert(str != NULL);
	if (*str != '\0')
		return 1 + my_strlen(str + 1);
	else
		return 0;
}

//指针-指针
int my_strlen2(const char* str)
{
	const char* start = str;
	assert(str != NULL);
	while (*str)
	{
		str++;
	}
	return str - start;
}

int my_strlen(const char* str)
{
	assert(str != NULL);//断言有效性
	int count = 0;
	while (*str != '\0')
	{
		count++;
		str++;
	}
	return count;
}



注:

strlen 是求字符串长度的,求出的长度是不可能为负数的
所以返回类型设置为size_t 也是合情合理的
typedef unsigned int size_t

size_t strlen(const char* string);

int main()
{
	char arr[] = "abcdef";
	int len = my_strlen(arr);
	printf("%d\n", len);

	return 0;
}
#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-strlen也是无符号 

int main()
{
	//3-6=-3
	//
	if (strlen("abc") - strlen("abcdef") > 0)
	{
		printf(">\n");
	}
	else
	{
		printf("<=\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为常量)。
✳学会模拟实现

char* my_strcpy(char* dest, const char* src)
{
	char* ret = dest;
	assert(dest && src);//不为空指针
	while (*dest++ = *src++)//为\0,此时为假
	{
		;
	}
	return ret;
}

int main()
{
	char arr1[20] = "";
	//char* p = "abcdefghiqwer";
	char arr2[] = "hello bit";
	my_strcpy(arr1, arr2);
	printf("%s\n", arr1);
	return 0;
}


 1.3 strcat

//在一个字符串后面追加一个字符串

char * strcat ( char * destination, const char * source );//原型与strcpy一样

✳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' 结束。
目标空间必须有足够的大,能容纳下源字符串的内容
目标空间必须可修改
✳模拟实现

//strcat
//字符串追加的
//
char* my_strcat(char* dest, const char* src)
{
	assert(dest && src);
	char* ret = dest;

	//1. 找目标空间的\0
	while (*dest)
	{
		dest++;
	}
	//2. 追加
	while (*dest++ = *src++)//赋值
	{
		;
	}
	return ret;
}


int main()
{
	char arr[20] = "hello ";
	//char arr2[] = "world";
	char* p = "world";
	my_strcat(arr, p);

	printf("%s\n", arr);

	return 0;
}

//自己给自己追加可能出现bug,不要用strcat这个函数 

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.

//一一对应
✳标准规定:
1.第一个字符串大于第二个字符串,则返回大于0的数字//1
2.第一个字符串等于第二个字符串,则返回0//0
3.第一个字符串小于第二个字符串,则返回小于0的数字//-1//vs情况

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


int main()
{
	char arr1[] = "abq";
	char arr2[] = "abcdef";
	//VS环境下:
	//> 1 
	//= 0 
	//< -1
	int ret = my_strcmp(arr1, arr2);

	if (ret>0)
		printf("arr1>arr2\n");

	printf("%d\n", ret);

	return 0;
}

//strcpy strcat strcmp长度不受限制的字符串函数(会被认为不安全,因为数组大小不够,还会一直追加。

//引入长度受限制函数:strncpy  

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

/* strncat example */
#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;
}

1.7 strncmp

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

//比较前num个 

/* strncmp example */
#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;
}

1.8 strstr

//查找字符串1里是否有字符串2

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

//在str1找str2

//返回str2在str1第一次出现的位置

模拟

char* my_strstr(const char* str1, const char* str2)
{
	assert(str1 && str2);//断言非空
	if (*str2 == '\0')
	{
		return (char*)str1;
	}
	const char* s1 = NULL;
	const char* s2 = NULL;
	const char* cp = str1;

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

	return NULL;
}

//需要创造指针保存起始位置 

//不要让str往后走,可以找个替代品使其往后走

/* strstr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a simple string";
char * pch;
pch = strstr (str,"simple");
strncpy (pch,"sample",6);
puts (str);
return 0;
}

1.9 strtok

//用法:切割为几个部分

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

✳sep参数是个字符串,定义了用作分隔符的字符集合
✳第一个参数指定一个字符串,它包含了0个或者多个由sep字符串中一个或者多个分隔符分割的标

✳strtok函数找到str中的下一个标记,并将其用 \0 结尾,返回一个指向这个标记的指针。(注:
strtok函数会改变被操作的字符串(arr),所以在使用strtok函数切分的字符串一般都是临时拷贝的内容
并且可修改。)
✳strtok函数的第一个参数不为 NULL ,函数将找到str中第一个标记,strtok函数将保存它在字符串
中的位置。
strtok函数的第一个参数为 NULL ,函数将在同一个字符串中被保存的位置开始,查找下一个标
记。

✳如果字符串中不存在更多的标记,则返回 NULL 指针。

int main()
{
	//char arr[] = "zpengwei@yeah.net";//"@."
	char arr[] = "192#168.120.85";
	char* p = "#.";
	char buf[20] = { 0 };//"zpengwei\0yeah\0net"
	strcpy(buf, arr);
	char* ret = NULL;
	for (ret = strtok(buf, p); ret != NULL; ret=strtok(NULL, p))
	{
		printf("%s\n", ret);
	}
	
	//char* ret = strtok(buf, p);
	//printf("%s\n", ret);
	//ret = strtok(NULL, p);//找到后面的yeah net
	//printf("%s\n", ret);
	//ret = strtok(NULL, p);
	//printf("%s\n", ret);

	//zpengwei
	//yeah
	//net
	return 0;
}
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
#include <stdio.h>
int main()
{
char *p = "zhangpengwei@bitedu.tech";
const char* sep = ".@";
char arr[30];
char *str = NULL;
strcpy(arr, p);//将数据拷贝一份,处理arr数组的内容
for(str=strtok(arr, sep); str != NULL; str=strtok(NULL, sep))
{
printf("%s\n", str);
}
}

1.10 strerror

char * strerror ( int errnum ); 

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

//获得指针指向错误信息

//C语言的库函数在运行的时候,如果发生错误,就会将错误码存在一个变量中,这个变量是:errno

//错误码是一些数字:1 2 3 4 5

//我们需要讲错误码翻译成错误信息

int main()
{
	printf("%s\n", strerror(0));
	printf("%s\n", strerror(1));
	printf("%s\n", strerror(2));
	printf("%s\n", strerror(3));
	printf("%s\n", strerror(4));
	printf("%s\n", strerror(5));

	return 0;
}

 

fopen函数 

//打开文件

 

//如果打开文件成功,就返回一个有效的指 针
//如果打开失败,返回一个NULL指针的 

#include <errno.h>

int main()
{
	//打开文件
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		//printf("%s\n", strerror(errno));
		perror("fopen");
		return 1;
	}
	//读文件
	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

 fopen直接打印错误信息

//perror是直接打印错误信息,在打印错误信息前,会先打印自定义的信息

//perror== printf + strerror

 字符分类函数:

函数如果他的参数符合下列条件就返回真
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任何可打印字符,包括图形字符和空白字符

//上述函数是检测作用,如果不是返回为0,是返回非零数字 

#include <ctype.h>

int main()
{
	int ret = isdigit('Q');
	printf("%d\n", ret);

	return 0;
}

字符转换:

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

//把一串字符,是大写的转化成小写 

/* isupper example */
#include <stdio.h>
#include <ctype.h>
int main()
{
	int i = 0;
	char str[] = "Test String.\n";
	char c;
	while (str[i])
	{
		c = str[i];
		if (isupper(c))
			c = tolower(c);
		putchar(c);
		i++;
	}
	return 0;
}
//I Have An Apple.
int main()
{
	char arr[] = "I Have An Apple.";
	int i = 0;
	while (arr[i])
	{
		if (isupper(arr[i]))
		{
			arr[i] = tolower(arr[i]);
		}
		printf("%c", arr[i]);
		i++;
	}
	return 0;
}

1.11 memcpy

memcpy//针对内存

strcpy//只能拷贝字符串

void * memcpy ( void * destination, const void * source, size_t num );//num拷贝的字节

✳函数memcpy从source的位置开始向后复制num个字节的数据到destination的内存位置。
✳这个函数在遇到 '\0' 的时候并不会停下来。
✳如果source和destination有任何的重叠,复制的结果都是未定义的

/* memcpy example */
#include <stdio.h>
#include <string.h>
struct {
	char name[40];
	int age;
} person, person_copy;
int main()
{
	char myname[] = "Pierre de Fermat";
	/* using memcpy to copy string: */
	memcpy(person.name, myname, strlen(myname) + 1);
	person.age = 46;
	/* using memcpy to copy structure: */
	memcpy(&person_copy, &person, sizeof(person));
	printf("person_copy: %s, %d \n", person_copy.name, person_copy.age);
	return 0;
}

//模拟函数 

//自身拷贝自身

//重叠情况

//若src在dest前面,从后往前

//若dest在src前面,从前往后

//不重叠,从前往后,从后往前都可以

可以以前面为边界,从前向后,后者从后向前 

//库函数(memove可以实现重叠拷贝)

//保证后面有足够的空间在考虑

#include <stdio.h>
#include <string.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;
}

void test2()//自身传递自身,发生重叠现象
{
	int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
	my_memcpy(arr1 + 2, arr1, 20);
}
//可以从后往前拷贝
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;
}


void test3()
{
	int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
	my_memmove(arr1+2, arr1, 20);
}

void test4()
{
	int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
	memcpy(arr1, arr1+2, 20);
}

int main()
{
	test4();
	return 0;
}

int main()
{
	int arr1[] = { 1,2,6 };//01 00 00 00 02 00 00 00 06 00 00 00
	int arr2[] = { 1,2,5 };//01 00 00 00 02 00 00 00 05 00 00 00
	int ret = memcmp(arr1, arr2, 9);
	printf("%d\n", ret);

	return 0;
}

1.12 memmove
 

void * memmove ( void * destination, const void * source, size_t num );

✳和memcpy的差别就是memmove函数处理的源内存块和目标内存块是可以重叠的。
✳如果源空间和目标空间出现重叠,就得使用memmove函数处理。
 

/* memmove example */
#include <stdio.h>
#include <string.h>
int main()
{
	char str[] = "memmove can be very useful......";
	memmove(str + 20, str + 15, 11);
	puts(str);
	return 0;
}

 1.13 memcmp

int memcmp ( const void * p
const void * p
size_t num );


比较从ptr1和ptr2指针开始的num个字节
返回值如下:

/* memcmp example */
#include <stdio.h>
#include <string.h>
int main()
{
	char buffer1[] = "DWgaOtP12df0";
	char buffer2[] = "DWGAOTP12DF0";
	int n;
	n = memcmp(buffer1, buffer2, sizeof(buffer1));
	if (n > 0) printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
	else if (n < 0) printf("'%s' is less than '%s'.\n", buffer1, buffer2);
	else printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
	return 0;
}

1.14 memset函数 

//以字节为设置

int main()
{
	char arr[] = "hello world";
	memset(arr, 'x', 5);
	printf("%s\n", arr);
	memset(arr+6, 'y', 5);
	printf("%s\n", arr);

	//int arr[10] = { 0 };
	//memset(arr, 0, 40);

	return 0;
}

2. 库函数的模拟实现
2.1 模拟实现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;
}

2.2 模拟实现strcpy
 

参考代码:
 

//1.参数顺序
//2.函数的功能,停止条件
//3.assert
//4.const修饰指针
//5.函数返回值
//6.题目出自《高质量C/C++编程》书籍最后的试题部分
char* my_strcpy(char* dest, const char* src)
{
	char* ret = dest;
	assert(dest != NULL);
	assert(src != NULL);
	while ((*dest++ = *src++))
	{
		;
	}
	return ret;
}

2.3 模拟实现strcat


参考代码:
 

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

2.4 模拟实现strstr
 

char* strstr(const char* str1, const char* str2)
{
	char* cp = (char*)str1;
	char* s1, * s2;
	if (!*str2)
		return((char*)str1);
	while (*cp)
	{
		s1 = cp;
		s2 = (char*)str2;
		while (*s1 && *s2 && !(*s1 - *s2))
			s1++, s2++;
		if (!*s2)
			return(cp);
		cp++;
	}
	return(NULL);
}


2.5 模拟实现strcmp

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) && *
		++src, ++dst;
	if (ret < 0)
		ret = -1;
	else if (ret > 0)
		ret = 1;
	return(ret);
}

2.6 模拟实现memcpy

void* memcpy(void* dst, const void* src, size_t count)
{
	void* ret = dst;
	assert(dst);
	assert(src);
	/*
	* copy from lower addresses to higher addresses
	*/
	while (count--) {
		*(char*)dst = *(char*)src;
		dst = (char*)dst + 1;
		src = (char*)src + 1;
	}
	return(ret);
}

2.7 模拟实现memmove

void* memmove(void* dst, const void* src, size_t count)
{
	void* ret = dst;
	if (dst <= src || (char*)dst >= ((char*)src + count)) {
		/*
		* Non-Overlapping Buffers
		* copy from lower addresses to higher addresses
*/
		while (count--) {
			*(char*)dst = *(char*)src;
			dst = (char*)dst + 1;
			src = (char*)src + 1;
		}
	}
	else {
		/*
		* Overlapping Buffers
		* copy from higher addresses to lower addresses
		*/
		dst = (char*)dst + count - 1;
		src = (char*)src + count - 1;
		while (count--) {
			*(char*)dst = *(char*)src;
			dst = (char*)dst - 1;
			src = (char*)src - 1;
		}
	}
	return(ret);
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值