c primer plus第11章总结:字符串和字符串函数

来源:互联网 发布:软件设计师怎么考 编辑:程序博客网 时间:2024/05/21 11:27

字符串数组的初始化:

char m1[40] = "Im  righe!";          // 注意分配空间大小;char m2[] = { 'y', 'o', 'u', '\0'}; // 如果没有结束符,只是字符数组,不是字符串数组;

字符数组名也是数组元素的首地址,则有:

m1 == &m1[0] , *m1 == m1[0], *( m1+1) == m1[1]

注:字符串是以空字符\0结尾的char数组;字符串数组能直接打印;

字符串数组:

数组初始化是从静态区域把字符串复制给数组;数组名m1==&m1[0];m1是地址常量,可以使用m1+1来标示下一个元素,但不允许用++m1;(增量运算符只能用在变量名前,不能用在常量前)

指针数组:

指针初始化是复制字符串的地址;数组名m1是指针变量,初始是指向第一个字符m1==&m1[0] ;可以使用m1+1来标示下一个元素,也允许用++m1;
  • 指针可以被数组赋值,但数组不能被指针赋值;
  • 指针数组,建议初始化为const;
  • 数组的元素是变量,但数组名不是变量;

指针赋值:

    char* string = "I'm right!";或:    char note[] = "see you ";    char* string = note;注:char note[] = "I'm right!"; // 字符串数组  与以下等价:char* node = "I'm right!";  // 指针数组                             // 指针传参时候需要用到note(首地址)或 &note[0](第一个元素取地址);char* string[] = {"I'm right!", "1111"}; // 指针加[],表示字符串指针数组,二维;                                         // 指针传参时候需要用到string[]
  • char string[] 作为形式参数,实参是数组名; const char* string
  • 作为形式参数,实参可以是数组名、引起来的字符串;

注:return 指针时,由于指针传参时候是复制地址, 被调函数中地址是临时创建,不能直接被返回,需要用new创建指针;常量传参时是复制值,可以直接return;

char* ptr = new char[N]; // 创建指针,分配内存;ptr = "I'm right!";return  ptr;注意:delete[] ptr;         // 只能delete 指针

常用函数介绍:

gets()函数:

需要有参数,返回读入字符串的地址;遇到文件结尾,返回空地址;特点:遇换行符停止,但会丢弃换行符;缺点:不检查是否超出存储区;

fgets()函数:

fgets(ar, n, stdin);可限制最多读取n-1个字符;
  • 主要是文件读取,也可以用stdin表示从键盘读取;
  • 遇换行符停止,但换行符会存到字符串中;

scanf()函数:

scanf()主要用于混合类型数据的读取和转换;

puts()函数:

需要给出字符串参数的地址,输出地址中对应值;特点:自动添加换行符;遇空字符停止;

fputs()函数:

需要第二个参数说明要写的文件,stdout屏幕输出显示;特点:不自动添加换行符;

自定义输入输出:

while(*string// 等同于*string != '\0';注意没有换行打印;     putchar(*string++);   // ++优先级高于*;*优先级高于+;

strlen()函数:

得到字符串长度(不含\0),可以缩短字符串长度;
if (strlen(string) > size)     *(string + size) = '\0';

strcat()函数:

拷贝连接两个字符串,但第二个字符串并未改变;缺点:不检查是否能容纳;
char flower[size];if ((strlen(addon) + strlen(flower) + 1) < size)     strcat(flower, addon)

strncat()函数:

需第三个参数来指明最多允许添加的字符数目;
char flower[size];availible = size - strlen(flower) - 1;strncat(flower, addon, availible );

strcmp()函数:

比较字符串,而非数组地址或字符;可以比较不同大小的字符串数组;比较值相同,返回0,;前值顺序先于后值,返回负数;前值顺序后于后值,返回正数;

strncmp()函数:

可限制比较的字符串长度;

strcpy()函数:

参数为地址:等价于赋值运算,属于char* 类;返回第一个参数的值,另外第一个参数不需要指向数组的开始,可只复制数组的一部分;ps = strcpy(copy + 7, orig);

atoi()函数

将字符串为参数,返回相应的整数值;

读取文件内容

//方法一:fread(file, len, 1, fp);  //一次性读取文件全部内容// 方法二:while ((ch = getc(fp)) != EOF){      //*file++ = ch;     putchar(ch);} 

课后习题

注:myfgets()函数定义在本文末尾段,功能类似gets()函数;有什么区别?myfgets可以获取任意输入长度字符串,解决gets获取长度有限的缺点。

第三题:读取输入行里的第一个单词到数组,丢弃剩余部分

char *get_words(){    int i = 0;    char ar[32];     printf("Input some words and save the first word in an array.\n");    char* ptr = myfgets();    // 本身就不读换行符    int len = strlen(ptr);    char* words = new char[len+1];    while (i < len && ptr[i] != ' ' && ptr[i] != '\t' && ptr[i] != '\0')    {        words[i]= ptr[i];        i++;    }    words[i] = '\0';    delete[] ptr;    return words;}

第15题:读取输入,直到文件结尾,并识别输入要求,打印文件内容;

void main(){    {        FILE * fp;        char fname[256];                            // 保存文件名        printf("Enter the name of the file: \n");        while (scanf("%s", fname) == 1)             // 文件名可输入相对路径,例:../a.txt            {            fp = fopen(fname, "r");             if (fp == NULL)                     {                printf("Failed to open file.please input right file name:\n");                      continue;            }            clearBuffer();            printf("Enter show file type. (and \"q\" to quit).\n");            char *show_type = myfgets();            // 输入文件显示类型            if ('q' == *show_type)                break;            show_file(fname, show_type);           // 根据文件名、类型,打印文件内容            printf("\n");            delete[] show_type;            fclose(fp);         }    }}// 输入文件名,获取文件内容,存入数组;char* get_file(char* filename){    int ch = 0;     FILE * fp = fopen(filename, "r+");     fseek(fp,0,SEEK_END);               // fseek和ftell计算文件内容长度;    int len = ftell(fp);    char* file = new char[len + 1];    fseek(fp,0,SEEK_SET);               // 指针指回首地址出;    fread(file, len, 1, fp);            // 一次性读取全部文件内容;     file[len] = '\0';    printf("Attention:%s file = \"%s\".\n",filename, file);    return file;}// 根据文件名、显示类型,显示文件内容void show_file(char* file_name, char* show_type){    char* file = get_file(file_name);    int len = strlen(file);    if (strcmp(show_type , "-p") == 0)        puts(file);    if (strcmp(show_type , "-u") == 0)    {        for(int i = 0; i < len; i++)            putchar(toupper(file[i]));    }    if (strcmp(show_type , "-l") == 0)    {        for(int i = 0; i < len; i++)            putchar(tolower(file[i]));    }}
// 从获取键盘输入的字符串,不含换行符;改写gets()函数;#include "stdafx.h"#include <string.h>struct mystring{    mystring()    {        size = MAX_LEN;        str = new char[size];        memset(str, 0x00, size);   // 内存空间初始化    ~mystring()    {        delete[] str;    }    char* detach()    {        char* ptr = str;        str = NULL;        size = 0;        return ptr;    }    size_t length() const    {        return strlen(str);    }    void copy(const mystring& other)    {        size_t len = other.length();        if (len >= size)        {            delete[] str;            size = len + 1;            str = new char[size];            memset(str, 0x00, size);        }        strcpy(str, other.str);    }    mystring(const char* other)    {        size_t len = strlen(other);        size = len + 1;        str = new char[size];        memset(str, 0x00, size);        strcpy(str, other);    }    mystring(const mystring& other)    {        copy(other);    }    mystring& operator=(const mystring& other)    {        if (&other == this)        {            return *this;        }        copy(other);        return *this;    }    mystring& operator+=(const mystring& other)    {        size_t len = other.length();        len += length();        if (len < size)        {            strcat(str, other.str);        }        else        {            size = len + 1;            char* strNew = new char[size];            memset(strNew, 0x00, size);            strcpy(strNew, str);            strcat(strNew, other.str);            delete[] str;            str = strNew;        }        return *this;    }protected:    char* str;    int size;};// 读取字符串直到换行符char* myfgets(){    mystring ms;    while (true)    {        char temp[MAX_LEN + 1] = { 0 };        fgets(temp, MAX_LEN, stdin);        int len = strlen(temp);        if (temp[len - 1] == 10)        {            temp[len - 1] = 0;            ms += temp;            break;        }        else        {            ms += temp;        }    }    // 由于读进了所有内容,不必调用clearBuffer    return ms.detach();}int _tmain(int argc, _TCHAR* argv[]){    char* ptr = myfgets();    printf("%s\n", ptr);    delete[] ptr;    return 0;}
0 0