字符函数和字符串函数

目录

求字符串长度

strlen

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

strcpy

strcat

strcmp

长度受限制的字符串函数

strncpy

strncat

strncmp

字符串查找

strstr

strtok

错误信息报告

strerror

内存操作函数

memcpy

memmove

memset

memcmp


本篇博客将介绍处理字符和字符串的库函数的使用和注意事项

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

求字符串长度

strlen

size_t strlen ( const char * str );

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

使用strlen函数

#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

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

size_t my_strlen(const char *string)
{
	assert(string != NULL);
	int count = 0;
	while ((*string++) != '\0')
		count++;
	return count;
}

void main()
{
	char str[] = { 'a', 'b', 'c', 'd', '\0' };
	const char *p = str;
	int res = my_strlen(p);
	printf("%d\n", res);
}

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

strcpy

char* strcpy(char * destination, const char * source );
  • 源字符串必须以 '\0' 结束。
  • 会将源字符串中的 '\0' 拷贝到目标空间。
  • 目标空间必须足够大,以确保能存放源字符串。
  • 目标空间必须可变。

使用strcpy函数

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

void main()
{
	char str[100] = "Hello";
	const char* str1 = "Bit";
	puts(strcpy(str, str1));
}

模拟实现strcpy函数

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

char* my_strcpy(char *strDestination, const char *strSource)
{
	assert(strDestination != NULL && strSource != NULL);
	char *pDest = strDestination;
	const char *pSce = strSource;
	while (*pSce != '\0')
		*pDest++ = *pSce++;
	*pDest = *pSce;
	return strDestination;
}

void main()
{
	char str1[] = "abcdef";
	const char *str2 = "asdf";
	my_strcpy(str1, str2);
	printf("%s\n", str1);
}

strcat

char * strcat ( char * destination, const char * source );
  • 源字符串必须以 '\0' 结束。
  • 目标空间必须有足够的大,能容纳下源字符串的内容。
  • 目标空间必须可修改。

使用strcat函数

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

void main()
{
	char str[100] = "Hello";
	const char* str1 = "Bit";
	puts(strcat(str, str1));
}

模拟实现strcat函数

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

char* my_strcat(char *strDestination, const char *strSource)
{
	assert(strDestination != NULL && strSource != NULL);
	char *pDest = strDestination;
	const char *pSce = strSource;
	while (*pDest != '\0')
		pDest++;
	while (*pSce != '\0')
		*pDest++ = *pSce++;
	*pDest = *pSce;
	return strDestination;
}

void main()
{
	char str1[100] = "asdf";
	const char *str2 = "hsbh";
	my_strcat(str1, str2);
	printf("%s\n", str1);
}

在使用过程中,我们发现在连接自己时,程序出现了bug,什么原因呢?

        我们在调用strcat函数时,传入的字符串通过指针访问字符串的地址,当我们用第一个字符替换末尾的"\0"后,原字符串已无"\0",则会造成死循环。

strcmp

int strcmp ( const char * str1, const char * str2 );
  • 第一个字符串大于第二个字符串,则返回大于0的数字
  • 第一个字符串等于第二个字符串,则返回0
  • 第一个字符串小于第二个字符串,则返回小于0的数字

使用strcmp函数

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

void main()
{
	const char* str = "Hello";
	const char* str1 = "Bit";
	printf("%d\n",strcmp(str, str1));
}

模拟实现strcmp函数

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

int my_strcmp(const char *string1, const char *string2)
{
	assert(string1!=NULL && string2!=NULL);
	while ((*string1 != '\0') && (*string2 != '\0'))
	{
		if (*string1 < *string2)
		{
			return -1;
		}
		else if (*string1>*string2)
		{
			return 1;
		}
		else
		{
			++string1;
			++string2;
		}
	}
	if (*string1 < *string2)
	{
		return -1;
	}
	else if (*string1>*string2)
	{
		return 1;
	}
	return 0;
}

void main()
{
	const char* str1 = "asdf";
	const char* str2 = "djshfs";
	int res = my_strcmp(str1, str2);
	if (res = 1)
		printf("str1 > str2\n");
	else if (res = 0)
		printf("str1 = str2\n");
	else
		printf("str1 < str2\n");
}

长度受限制的字符串函数

strncpy

char * strncpy ( char * destination, const char * source, size_t num );
  • 拷贝num个字符从源字符串到目标空间。
  • 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。

使用strncpy函数

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

void main()
{
	char str[100] = "Hello";
	const char* str1 = "Bit";
	puts(strncpy(str, str1,2));
}

模拟实现strncpy函数

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

char* my_strncpy(char * destination, const char * source, size_t num)
{
	assert(destination != NULL && source != NULL);
	char *pDest = destination;
	const char *pSce = source;
	while (num--)
		*pDest++ = *pSce++;
	if (strlen(destination) < num)
		*pDest = '\0';
	return destination;
}

void main()
{
	char arr1[50] = "bit";
	char arr2[] = "pouces";
	printf("%s\n", my_strncpy(arr1, arr2, 4));
}

strncat

char * strncat ( char * destination, const char * source, size_t num );

使用strncat函数

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

void main()
{
	char str[100] = "Hello";
	const char* str1 = "Bit";
	puts(strncat(str, str1,2));
}

模拟实现strncat函数

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

char* my_strncat(char * destination, const char * source, size_t num)
{
	assert(destination != NULL && source != NULL);
	char *pDest = destination;
	const char *pSce = source;
	while (*pDest != '\0')
		pDest++;
	while (num--)
		*pDest++ = *pSce++;
	return destination;
}

void main()
{
	char str1[100] = "asdf";
	const char *str2 = "hsbh";
	printf("%s\n", my_strncat(str1, str2,2));
}

strncmp

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

使用strncmp函数

#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;
}

模拟实现strncmp函数

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

int my_strncmp(const char *str1, const char *str2,size_t num)
{
	assert(str1 != NULL && str2 != NULL);
	while (num > 0)
	{
		if (*str1 < *str2)
		{
			return -1;
		}
		else if (*str1>*str2)
		{
			return 1;
		}
		else
		{
			++str1;
			++str2;
		}
		num--;
	}
	return 0;
}

void main()
{
	const char* str1 = "asdf";
	const char* str2 = "djshfs";
	int res = my_strncmp(str1, str2,3);
	if (res = 1)
		printf("str1 > str2\n");
	else if (res = 0)
		printf("str1 = str2\n");
	else
		printf("str1 < str2\n");
}

字符串查找

strstr

char *strstr( const char *string, const char *strCharSet );

使用strstr函数

#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(pch);
	return 0;
}

这个函数找到字串后会从找到的字串一直输出直到找到’\0’为止

模拟实现strstr函数

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

char* my_strstr(const char *string, const char *strCharSet)
{
	assert(string && strCharSet);
	const char *str1 = NULL;
	const char *str2 = NULL;
	const char *str3 = string;
	if (*strCharSet == '\0')
		return (char*)string;
	while (*str3 != '\0')
	{
		str1 = str3;
		str2 = strCharSet;
		while (*str1 == *str2)
		{
			str1++;
			str2++;
		}
		if (*str2 == '\0')
			return (char*)str3;
		str3++;
	}
	return NULL;
}

void main()
{
	char str[] = "This is a simple string";
	char* pch;
	pch = my_strstr(str, "simple");
	puts(pch);
}

strtok

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

使用strtok函数

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

错误信息报告

strerror

char *strerror( int errnum );
  • 返回错误码,所对应的错误信息。

使用strerror函数

#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;
}

内存操作函数

memcpy

void *memcpy( void *dest, const void *src, size_t count );
  • 函数memcpysource的位置开始向后复制num个字节的数据到destination的内存位置。
  • 这个函数在遇到 '\0' 的时候并不会停下来。
  • 如果sourcedestination有任何的重叠,复制的结果都是未定义的。

使用memcpy函数

#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;
}

模拟实现memcpy函数

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

void* my_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);
}

struct {
	char name[40];
	int age;
} person, person_copy;

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

memmove

void *memmove( void *dest, const void *src, size_t count );
  • memcpy的差别就是memmove函数处理的源内存块和目标内存块是可以重叠的。
  • 如果源空间和目标空间出现重叠,就得使用memmove函数处理。

使用memmove函数

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

int main()
{
	char str[] = "memmove can be very useful......";
	memmove(str + 20, str + 15, 11);
	puts(str + 20);
	return 0;
}

模拟实现memmove函数

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

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);
}

int main()
{
	char str[] = "memmove can be very useful......";
	memmove(str + 20, str + 15, 11);
	puts(str + 20);
	return 0;
}

memset

void *memset( void *dest, int c, size_t count );

使用memset函数

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

int main(){
	char a[4];
	memset(a, '1', 4);
	for (int i = 0; i<4; i++){
		printf("%c\n", a[i]);
	}
	return 0;
}

memcmp

int memcmp( const void *buf1, const void *buf2, size_t count );
  • 比较从buf1和buf2指针开始的num个字节

使用memcmp函数

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mᴇᴇᴛ ꦿ᭄.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值