字符函数和字符串函数详解

前言

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的返回值是无符号的。
在这里插入图片描述

strlen实现

// 方式一:指针-指针方式
#include<stdio.h>
#include<windows.h>
int my_strlen(char *str) {
	//int count = 0;
	char * tmp = str;
	while (*tmp != '\0') {
		//count++;
		tmp++;
	}
	return tmp-str;
}

// 方式二:计数器方式
int my_strlen(const char * str)
{
	int count = 0;
	while(*str)
	{
		count++;
		str++;
	}
	return count;
}
// 方式三:递归
int my_strlen(const char * str)
{
	if(*str == '\0')
		return 0;
	else
		return 1+my_strlen(str+1);
}


int main() {
	const char*str1 = "qsbqidgiqdgi";
	int a = my_strlen(str1);
	system("pause");
	return 0;
}

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’ 拷贝到目标空间。
  • 目标空间必须足够大,以确保能存放源字符串。
  • 目标空间必须可变。
  • 学会模拟实现。

strcpy实现

// 写法一:
char* my_strcpy(char *dec,char* src) {
	char * tmp = dec;
	while (*src != '\0') {
		*dec = *src;
		dec++;
		src++;
	}
	*dec = '\0';
	return tmp;
}

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

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’ 结束。
  • 目标空间必须有足够的大,能容纳下源字符串的内容。
  • 目标空间必须可修改。
  • 字符串自己给自己追加,如何?

strcat实现

char* my_strcat(char* des, char* src) {
	char*tmp = des;
	while (*des != '\0') {
		des++;;
	}
	while (*src != '\0') {
		*des = *src;
		des++;
		src++;
	}
	return tmp;
}

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的数字
  • 那么如何判断两个字符串?

strcmp实现


int my_strcmp(char *str,char *str1) {
	while (*str1 != '\0' && *str != '\0') {
		if (*str != *str1 ) {
			return (*str - *str1) > 0 ? 1 :  -1;
		}
		str++;
		str1++;
	}
	if (*str == '\0') {
		return -1;
	}
	else if(*str1 == '\0') {
		return 1;
	}
	return 0;
}

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

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 nullcharacter is copied.
#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;
}

运行结果:

To be or not

strncmp介绍

int strncmp ( const char * str1, const char * str2, size_t num );
  • 比较到出现另个字符不一样或者一个字符串结束或者num个字符全部比较完
  • 返回值
return valueindicates
<0the first character that does not match has a lower value in str1 than in str2
0the contents of both strings are equal
>0the first character that does not match has a greater value in str1 than in str2
/* 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;
}

运行结果:

Looking for R2 astromech droids...
found R2D2
found R2A6

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.
  • The matching process does not include the terminating null-characters, but it stops there.
/* strstr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="This is a simple string";
  char * pch;
  pch = strstr (str,"simple");//字串查找,返回值为字串首地址
  if (pch != NULL)
    strncpy (pch,"sample",6);
  puts (str);
  return 0;
}

运行结果:

This is a sample string

注意strstr的返回值:
在这里插入图片描述

strstr实现


char * my_strstr(const char * str, const char * str1) {
	if (*str1 == '\0') {
		return 0;
	}
	char *tmp = str;
	while (*tmp != '\0') {
		char *cp = tmp;
		while (*cp != '\0'&&*str1 != '\0' && *cp == *str1) {
			cp++;
			str1++;
		}
		if (*str1 == '\0') {
			return tmp;
		}
		tmp++;
	}
	return 0;
}

strtok介绍

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

运行结果:

Splitting string "- This, a sample string." into tokens:
This
a
sample
string

根据每行代码的执行来分析该函数是如何实现的:

char str[] ="- This, a sample string.";

在这里插入图片描述

pch = strtok (str," ,.-");

把对应的结尾位置置为==’\0’==
在这里插入图片描述

pch = strtok (NULL, " ,.-");

在这里插入图片描述
pch = strtok (NULL, " ,.-");在这里插入图片描述

strerror介绍

char * strerror ( int errnum );
  • Get pointer to error message string
/* 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));
  return 0;
}

输出:

Error opening file unexist.ent: No such file or directory

字符分类函数

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

字符转换

tolower 介绍

toupper介绍

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

示例代码;

/* tolower 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];
    putchar (tolower(c));
    i++;
  }
  return 0;
}

memcpy介绍

void * memcpy ( void * destination, const void * source, size_t 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;
}

运行结果:

person_copy: Pierre de Fermat, 46

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


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

运行结果:

memmove can be very very useful.

memmove实现




void * my_memmove(void * des, const void * src, int num) {
	char *_des = (char *)des;
	char *_src = (char *)src;
	
	if (_des > _src && (_des + num) < _src) {
		///从后往前移动
		_src = _src + num - 1;
		_des = _des + num - 1;
		while (num--) {
			*_des = *_src;
			_des--;
			_src--;
		}
	}
	else {
		// 从前往后移动
		while (num--) {
			*_des = *_src;
			_des++;
			_src++;
		}
	}


	return des;
}

memcmp介绍

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

  • 比较从ptr1和ptr2指针开始的num个字节
  • 返回值如下:
return valueindicates
<0the first byte that does not match in both memory blocks has a lower value in ptr1 than in ptr2 (if evaluated as unsigned char values)
0the contents of both memory blocks are equal
>0the first byte that does not match in both memory blocks has a greater value in ptr1 than in ptr2 (if evaluated as unsigned char values)
/* 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;
}

输出结果:

'DWgaOtP12df0' is greater than 'DWGAOTP12DF0'.
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值