BIT-3-字符函数和字符串函数(C语言进阶)

本章重点

重点介绍处理字符和字符串的库函数的使用和注意事项

  • 求字符串长度
    • strlen
  • 长度不受限制的字符串函数
    • strcpy
    • strcat
    • strcmp
  • 长度受限制的字符串函数介绍
    • strncpy
    • strncat
    • strncmp
  • 字符串查找
    • strstr
    • strtok
  • 错误信息报告
    • strerror
  • 字符操作
  • 内存操作函数
    • memcpy
    • memmove
    • memset
    • memcmp

0. 前言


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

1. 函数介绍


1.1 strlen

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

注:

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

结果:str2>str1
因为strlen函数的返回类型是size_t - 无符号整型

1.2strcpy

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

1.3strcat

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

字符串自己给自己追加:不行,因为是同一个数组,所以追加时从目标\0开始覆盖追加,就会发现源字符永远找不到\0停止,陷入无限追加。

#include
#include 

int main()
{
	char arr1[20] = "hello \0xxxxxxxxx";
	char arr2[] = "world";
	//追加
	strcat(arr1, arr2);
	printf("%s\n", arr1);

	return 0;
}

运行调试看看就理解了

1.4strcmp

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的数字(VS是1)
    • 第一个字符串等于第二个字符串,则返回0
    • 第一个字符串小于第二个字符串,则返回小于0的数字(VS是-1)
    • 那么如何判断两个字符串?
      • 两个字符串字符一 一比较,直到遇到第一个对应不一样的比较ASCII值,返回一个整型

注:比较2个字符串的内容的时候,不能使用==,应该使用strcmp

你可能感兴趣的:(C语言,c语言,开发语言,学习,算法,c++,青少年编程,字符函数和字符串函数)