字符串函数练习

字符串函数练习

一:下列程序会打印什么

  1. #include<stdio.h>
    int main(void)
    {
        char note[]="See you at the snack bar.";
        char *ptr;
        
        ptr=note;
        puts(ptr);
        puts(++ptr);
        note[7]='\0';\\只保留了字符串前七位
        puts(note);
        puts(++ptr);
        return 0;
    }
    ​

    打印结果:

    See you at the snack bar.
    ee you at the snack bar.
    See you
    e you
    ​

    puts(++ptr)表示从第二个元素e开始打印

    puts( )函数遇到空字符停止('\0')

     

  2. #include<stdio.h>
    #include<string.h>
    ​
    int main(void)
    {
        char food[]="Yummy";
        char *ptr;
        
        ptr=food+strlen(food);???
        while(--ptr>=food){
            puts(ptr);
        }
        return 0;
    }
    ​

打印结果:

y
my
mmy
ummy
Yummy
​

ptr=food+strlen(food)表示将指针指向food字符的最后一个元素(该元素是空字符\0)

  1. #include<stdio.h>
    #include<string.h>
    ​
    int main(void)
    {
        char goldwyn[40]="art of it all ";
        char samuel[40]="I read p";
        const char *quote="the way through.";
        
        strcat(goldwyn,quote);
        strcat(samuel,goldwyn);
        puts(samuel);
        return 0;
    }
    ​

打印结果:

I read part of it all the way through.

主要是strcat( )函数的使用,把第二个字符串加在第一个字符串末尾,并把拼接后形成的新字符串作为第一个字符串,第二个字符串不变。

  1. #include<stdio.h>
    ​
    char *pr(char *str)
    {
        char *pc;
        
        pc=str;
        while(*pc){
            putchar(*pc++);
        }//在while循环中,打印指针pc指向的字符串,直到*pc为0(即字符串末尾的空字符
        do{
            putchar(*--pc);
        }while(pc-str);//在do...while循环中,通过指针递减,将while循环已经移动到字符串末尾的指针重新向字符串头部倒序移动,用于逆序打印整个字符串
        return (pc);
    }

    考虑下面的函数调用: x=pr("Ho Ho Ho!");

    a. 将打印什么?

    将打印Ho Ho Ho!!oH oH oH

    b. x是什么类型?

    x与函数pr( )的返回值相同,均是char*

    c. x的值是什么?

    x的值即函数的返回值。通过两个循环,将局部变量pc指向函数参数字符串的首字符,所以x的值等于str。在函数调用中x指向字符串“Ho Ho Ho!”的首字母'H'

    d.表达式*--pc是什么意思?

    *--pc表示将pc指针递减1

    --*pc表示先取指针pc指向的储存区域中值,再做递减操作

    e.两个while循环用来测试什么?

    while(*pc)用来检测pc指针是否指向一个空字符,判断条件使用pc指向的地址中的数组

    while(pc-str)检测指针pc是否指向str字符串的头(即pc的地址是否和str的地址相等),判断条件使用指针pc内储存的地址值

     
posted @ 2023-03-12 20:45  Ninnne  阅读(72)  评论(0)    收藏  举报