C语言-第24课

第24课 - C语言中的字符串

从概念上讲,C语言没有字符串数据类型。

l C语言中使用字符数组来模拟字符串。

l C语言的字符串是以’’结束的字符数组。

l C语言中的字符串可以分配于栈空间、堆空间或只读存储区。

eg:

#include <stdio.h>

#include <malloc.h>

int main()

{

char s1[] = {'H', 'e', 'l', 'l', 'o'}; //栈空间,单纯的字符数组

char s2[] = {'H', 'e', 'l', 'l', 'o', ''}; //栈空间,字符串

char* s3 = "Hello";//只读存储区,其值不能被更改,类似于字符串常量。

char* s4 = (char*)malloc(6*sizeof(char)); //堆空间

    s4[0] = 'H';

    s4[1] = 'e';

    s4[2] = 'l';

    s4[3] = 'l';

    s4[4] = 'o';

    s4[5] = '';

    free(s4);

    return 0;

}

  1. 字符串长度

1字符串的长度就是字符串所包含字符的个数。

2C语言中的字符串长度指的是第一个’’字符前出现的字符个数。

3C语言中通过’结束符确定字符串的长度。

eg:

#include<stdio.h>

#include<string.h>

int main()

{

char s4[100];

    s4[0] = 'H';

    s4[1] = 'e';

    s4[2] = 'l';

    s4[3] = 'l';

    s4[4] = 'o';

    s4[5] = '';

printf("%d ",strlen(s4));

printf("%d ",sizeof(s4));

return 0;

运行结果:5

          100

注:字符串长度警告

char* a = ”123”;

char* b = “1234”;

if(strlen(a) >= strlen(b))

{ ///                }

if(strlen(a) - strlen(b) >= 0)

{ ///                }

strlen的返回值是用无符号数定义的,因此相减不可能产生负数,以上的语句不等价。

例题分析--使用一条语句实现strlen

size_t strlen(const char* s)

{

size_t length = 0;

assert(s);   //当指针为空的时候,在这里运行出错。

while(*s++)

{

length++;

}

return length;

}

这是正常的strlen函数,改变如下:

#include <stdio.h>

#include <assert.h>

size_t strlen(const char* s)

{

    return ( assert(s), (*s ? (strlen(s+1) + 1) : 0) );  //三步运算符和递归函数的使用,以//及逗号表达式的使用

}

int main()

{

    printf("%d ", strlen("hello"));  

    return 0;

}

运行结果:5

注:

一般情况下,千万不要自行编写C标准库已经提供的函数。

l 标准库有时会使用汇编语言来实现,目的就是充分利用机器所提供的特殊指令以追求最大的速度。

l 复用已经存在的函数库会更高效。

  1. 不受限制的字符串函数

1不受限制的字符串函数是通过寻找字符串的结束符'来判断长度:

字符串复制:char* strcpy(char* dst, const char* src);字符串的复制函数

字符串连接:char* strcat(char* dst, cosnt char* src);字符串的拼接函数

字符串比较:int strcmp(const char* s1, const char* s2);字符串的比较函数

2注意事项:

①不受限制的字符串函数都是以’’作为结尾标记来进行的,因此输入参数中必须包含''

strcpystrcat必须保证目标字符数组的剩余空间足以保持整个源字符串。

strcmp0值表示两个字符串相等。

第一个字符串大于第二个字符串的时候返回值大于0

第一个字符串小于第二个字符串的时候返回值小于0

故,下面这条程序是不对的:

if(strcmp(“1”,”1”))

printf(“12345”)

应该改为:

if(strcmp(“1”,”1”) == 0)

printf(“12345”)

练习题:实现strcpy,很重要

#include <stdio.h>

#include <assert.h>

char* strcpy_12(char* dst, const char* src)

{

    char* ret = dst;

    assert(dst && src); //安全的意识

    while( (*dst++ = *src++) != '' );  //效率

    return ret;

}

int main()

{

    char dst[20];

    printf("%s ", strcpy_12(dst, "Delphi Tang!"));

    return 0;

}

  1. 长度受限的字符串函数

工作中为了安全,我们要尽量使用长度受限制的字符串函数。

1长度受限的字符串函数接收一个显示的长度参数用于限定操作的字符数。

字符串复制:char* strncpy(char* dst, const char* src, size_t len);

字符串连接:char* strncat(char* dst, const char* src, size_t len);

字符串比较:int strncmp(const char* s1, const char*s2, size_t len);

2注意事项:

strncpy只复制len个字符到目标字符串。

当源字符串的长度小于len时,剩余的空间以’'填充。

当源字符串的长度大于len时,只有len个字符会被复制,且它不会以’’结束。

②、strncat最多从源字符串中复制len个字符到目标字符串中。

strncat总是在结果字符串后面添加‘'

strncat不会用’’填充目标字符串的剩余空间。

strncmp只比较len个字符是否相等。

原文地址:https://www.cnblogs.com/free-1122/p/9758905.html