C89:论常用的字符串函数

一.简介

 函数的定义不可以嵌套,但函数的调用可以嵌套

 

二.复制字符串

1.strcpy()

头文件:#include <string.h>和#include <stdio.h>

原型声明:char* strcpy(char* dest,const char* src);

 

strcpy是一种C语言的标准库函数,strcpy把含有'\0'结束符的字符串复制到另一个地址空间,返回值的类型为char*

//用法
char a[10],b[]="copy";
strcpy(a,b);    //将b中的copy到a中

char *pa=new char[10];
char *pb=b;
strcpy(pa,pb);
delete pa;

 

//C语言标准库函数strcpy的经典实现

#include <assert.h>    //C头文件
#include <cassert>     //C++头文件
char* strcpy(char* des,const char* src){
    char* r=des;
    assert((des!=NULL)&&(src!=NULL));
    while(*source++!='\0'){
        *r++=*source++;
    }
    return des;  //从函数中返回函数体内分配的内存是十分危险的,会导致内存泄漏
}

 

2.strcpy_s()

原型声明:errno_t strcpy_s(char* strDes,size_t num,const char* strSrc);

 

strcpy因为不安全会报警告,所以推荐使用strcpy_s

strcpy_s(pa,10,pb);

 

3.strncpy()

 

4.例子

char string[10];
char* str = "0123456789";
strcpy(string, str);

堆栈破坏,因为str多了结束字符'\0'

 

char string[10], str[10];
int i;
for(i = 0; i < 10; i++)
{
    str[i] = 'a';
}
strcpy(string, str);

没有结束字符

 

char string[10];
int a = strlen(str);
if (a <= 10)
{
    strcpy(string, str);
}

可能堆栈溢出,因为strlen不统计'\0'

 

//错误
void
GetMemory(char* p) { p = (char*) malloc(100); } int main() { char* str = NULL; GetMemory(str); strcpy(str, "hello"); }

//正确

void getmemory(char **p)

{

*p=(char*)malloc(100);

//p = new char[100];

memset(*p,'\0',sizeof(*p[0])*100);

}


int main(int argc, char *argv[])

{

char * str = NULL;

getmemory(&str);

strcpy(str,"hello,world");

printf("%s",str);

return 0;

}


动态分配内存在堆上,可用于函数外,但是指针未传出

 

char* GetMemory(void)
{
    char p[] = "hello";
    return p;
}


int main()
{
    char* str = NULL;
    str = GetMemory();
    //strcpy(str, "hello");
    printf(str);
    //printf("k5");
    system("pause");
    return 0;
}

打印乱码,没有字符串格式化

 

void GetMemory(char** p, int num)
{
    *p = (char*) malloc(num);
}


int main()
{
    char* str = NULL;
    GetMemory(&str, 100);
    strcpy(str, "hello");
    printf(str);
    //printf("k5");
    system("pause");
    return 0;
}

打印正确

 

void swap(int* p1,int* p2)
{
    int* p;
    *p = *p1;
    *p1 = *p2;
    *p2 = *p;
}

指针未初始化

 

三.格式化字符串

1.sprintf()

输出浮点数时,会按要求的或默认的精度进行四舍五入

 

2.printf()

 

四.剪切字符串

1.strcat()

 

五.比较字符串

1.strcmp()

 

六.统计字符串

1.strlen()

直到碰到第一个字符串结束符'\0'为止,然后返回计数器值(长度不包含'\0')

 

2.sizeof()

 包含结束字符的统计

posted @ 2019-06-27 14:32  言午丶  阅读(267)  评论(0编辑  收藏  举报