c语言常见字符串函数的使用和模拟实现

前言

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

目录

1.函数介绍

1.1 strlen
1.2 strcpy
1.3 strcat
1.4 strcmp
1.5 strncpy
1.6 strncat
1.7 strncmp
1.8 strstr
1.9 strtok
1.10 strerror
1.11 memcpy
1.12 memmove
1.13 memcmp

2.库函数的模拟实现

2.1 模拟实现 strlen
2.2 模拟实现 strcpy
2.3 模拟实现 strcat
2.4 模拟实现 strstr
2.5 模拟实现 strcmp
2.6 模拟实现 memcpy
2.7 模拟实现 memmove

1. 函数介绍

1.1 strlen

size_t strlen ( const char * str );

  1. 字符串已经 ‘\0’ 作为结束标志,strlen函数返回的是在字符串中 ‘\0’ 前面出现的字符个数(不包含 ‘\0’ )。
  2. 参数指向的字符串必须要以 ‘\0’ 结束。
  3. 注意函数的返回值为size_t,是无符号的( 易错 )

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).

  1. 源字符串必须以 ‘\0’ 结束。
  2. 会将源字符串中的 ‘\0’ 拷贝到目标空间。
  3. 目标空间必须足够大,以确保能存放源字符串。
  4. 目标空间必须可变。

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.

  1. 源字符串必须以 ‘\0’ 结束。
  2. 目标空间必须有足够的大,能容纳下源字符串的内容。
  3. 目标空间必须可修改。
  4. 字符串自己给自己追加,如何?

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的数字
  2. 第一个字符串等于第二个字符串,则返回0
  3. 第一个字符串小于第二个字符串,则返回小于0的数字

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.

  1. 拷贝num个字符从源字符串到目标空间。
  2. 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。

1.6 strcat

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

1.7 strncmp

int strncmp ( const char * str1, const char * str2, size_t 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

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 ofstr1.

/* 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 );

  1. sep参数是个字符串,定义了用作分隔符的字符集合第一个参数指定一个字符串,它包含了0个或者多个由sep字符串中一个或者多个分隔符分割的标记。
  2. strtok函数找到str中的下一个标记,并将其用 \0
    结尾,返回一个指向这个标记的指针。(注:strtok函数会改变被操作的字符串,所以在使用strtok函数切分的字符串一般都是临时拷贝的内容并且可修改。)
  3. strtok函数的第一个参数不为 NULL ,函数将找到str中第一个标记,strtok函数将保存它在字符串中的位置。
  4. strtok函数的第一个参数为 NULL ,函数将在同一个字符串中被保存的位置开始,查找下一个标记。
  5. 如果字符串中不存在更多的标记,则返回 NULL 指针。
/* 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;
}

1.10 strerror

char * strerror ( int errnum );

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

/* strerror example : error list */
#include <stdio.h>
#include <string.h>
#include <errno.h>//必须包含的头文件
int main ()
{
    
    

 FILE * pFile;
 pFile = fopen ("unexist.ent","r");
 if (pFile == NULL)
  printf ("Error opening file unexist.ent: %s\n",strerror(errno));
  //errno: Last error number
 return 0;
}

1.11 memcpy

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

  1. 函数memcpy从source的位置开始向后复制num个字节的数据到destination的内存位置。
  2. 这个函数在遇到 ‘\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;
}

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 * ptr1,
const void * ptr2,
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;
}

2 库函数的模拟实现

2.1 模拟实现strlen

#include<stdio.h>
#include<assert.h>
//模拟实现strlen函数
int my_strlen(char* str)
{
    
    
	//用断言检查str是否为空指针
	assert(str);
	//用count来记录字符串的长度
	int count = 0;
	while (*str!='\0')//如果str指向的内容为'\0'就跳出循环
	{
    
    
		count++;
		str++;
	}
	return count;
}
int main()
{
    
    
	char arr[] = "mystrlenfunction";
	printf("%d\n", my_strlen(arr));
	return 0;
}

运行结果如下:
在这里插入图片描述

2.2 模拟实现strcpy

#include<stdio.h>
#include<assert.h>
//模拟实现strcpy函数
char* my_strcpy(char* dest, const char* src)
{
    
    
	//如果dest 和 src 有一个是空指针就断言
	assert(dest && src);
	//把dest的原地址保存
	char* ret = dest;
	//把src里面的字符一个一个复制到dest,直到src='\0'时跳出循环
	while (*dest++=*src++)
	{
    
    
		;
	}
	//复制完之后返回原来字符数组的首元素地址
	return ret;
}
int main()
{
    
    
	char str1[] = "returnMyOffer";
	char str2[20] = "studyHard";
	printf("%s\n", my_strcpy(str2, str1));
	return 0;
}

代码运行结果如下:
在这里插入图片描述

2.3 模拟实现strcat

#include<stdio.h>
#include<assert.h>
//模拟实现strcat函数(字符串追加)
char* my_strcat(char* dest, const char* src)
{
    
    
	//如果dest 和 src 有一个是空指针就断言
	assert(dest && src);
	//把dest的原地址保存
	char* ret = dest;
	//从dest指向'\0'时开始追加,src = '\0'时停止追加
	while (*dest!='\0')
	{
    
    
		dest++;
	}
	while (*dest++ = *src++)
	{
    
    
		;
	}
	return ret;

}
int main()
{
    
    
	char arr1[50] = "return_my";
	char arr2[] = "offer";
	printf("%s\n", my_strcat(arr1, arr2));
	return 0;
}

代码运行结果如下:
在这里插入图片描述

2.4 模拟实现strstr

#include<stdio.h>
#include<assert.h>
//模拟实现strstr函数
char* my_strstr(const char* str1,const char* str2)
{
    
    
	assert(str1 && str2);
	if (*str1 == '\0')
	{
    
    
		return str1;
	}
	const char* s1 = NULL;
	const char* s2 = NULL;
	const char* cp = str1;
	
	while (*cp)
	{
    
    
		s1 = cp;
		s2 = str2;
		while (*s1 && *s2 && (*s1 == *s2))
		{
    
    
			s1++;
			s2++;
		}
		if (*s2 == '\0')
		{
    
    
			return (char*) cp;
		}
		cp++;
	}
	return NULL;//如果循环结束后没有找到说明没有,返回NULL
}
int main()
{
    
    
	char str1[] = "myoffferreturn";
	char str2[] = "ffer";
	char* ret = my_strstr(str1, str2);
	if (ret == NULL)
	{
    
    
		printf("没有找到\n");
	}
	else
	{
    
    
		printf("找到了,位置是:%s\n", ret);
	}
	return 0;

代码运行结果如下:
在这里插入图片描述

2.5 模拟实现strcmp

#include<stdio.h>
#include<assert.h>
//模拟实现strcmp函数
int my_strcmp(const char* arr1, const char* arr2)
{
    
    
	assert(arr1 && arr2);
	while (*arr1 == *arr2)
	{
    
    
		if (*arr1 == '\0')
		{
    
    
			return 0;
		}
		arr1++;
		arr2++;
	}
	return *arr1 - *arr2;//返回两个字符的ASCLL码的差值
	
}
int main()
{
    
    
	char arr1[] = "hellobit";
	char arr2[] = "hellobit";
	if (my_strcmp(arr1, arr2) == 0)
		printf("arr1==arr2\n");
	else if (my_strcmp(arr1, arr2) > 0)
	{
    
    
		printf("arr1>arr2\n");
	}
	else
		printf("arr1<arr2\n");
	return 0;
}

代码运行结果如下:
在这里插入图片描述

2.6 模拟实现 memcpy

#include<stdio.h>
#include<string.h>
#include<assert.h>
//模拟实现memcpy
void* my_memcpy(void* dest, const void* src, size_t num)
{
    
    
	assert(dest && src);
	void* ret = (char*)dest;//先把目的地的首地址存起来
	while (num--)
	{
    
    
		*(char*)dest = *(char*)src;//把源字符串一个字节一个字节的拷贝到目的字符串中
		dest = (char*)dest + 1;//拷贝之后往后移
		src = (char*)src + 1;
	}
	return ret;//返回拷贝后的目的地的首地址

}
//memcpy函数拷贝不重叠内存
int main()
{
    
    
	char arr1[] = "Return_MyOffer";
	char arr2[20] = "mypro";
	printf("%s\n", my_memcpy(arr2, arr1, 15));
	return 0;
}

代码运行结果如下:
在这里插入图片描述

2.7 模拟实现 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;
			src = (char*)src;

		}
	}
	else
	{
    
    
		//从后往前拷贝
		while (num--)
		{
    
    
			*((char*)dest + num) = *((char*)src + num);
		}
	}
	return ret;
}
int main()
{
    
    
	int arr1[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	my_memmove(arr1 + 2, arr1, 20);
	return 0;
}

代码运行结果所得到的监视窗口如下:
在这里插入图片描述

总结

猜你喜欢

转载自blog.csdn.net/weixin_63181097/article/details/129572260
今日推荐