zoukankan      html  css  js  c++  java
  • 字符串与指针{学习笔记}

    <<用字符指针指向一个字符串:

    #include <studio.h>
    void main()
    {
    char *string="hello,world!";
    printf("%s ",string );
    return;
    }

    例子:将字符串a复制成字符串b

    #include <studio.h>
    void main()
    {
    char a[]="i am a boy",b[20];
    int i;
    for (i=0;*(a+i)!='';i++)
    {
    *(b+i)=*(a+i);
    *(b+i)='';
    printf("string a is :%s ",a);
    printf("string b is :");
    for (i=0;b[i]!='';i++)
    {
    printf("%c",b[i]);
    printf(" ");
    }
    }
    }

    >>使用指针变量;

    #include <studio.h>
    void main()
    {
    char a[]="i am a boy",b[20],*p1,*p2;
    int i;
    p1=a;p2=b;
    for (;*p1!='';p1++,p2++)
    {
    *p2=*p1;
    *p2='';
    printf("string a is :%s ",a);
    printf("string b is :");
    }
    for (i=0;b[i]!='';i++)
    {
    printf("%c",b[i]);
    printf(" ");
    }
    return 0;
    }

    程序必须保证使p1和p2同步移动;

    字符指针作函数参数

    将一个字符串从一个函数传递到另一个函数,可以用地址传递的方法,即用字符数组名作参数,也可以用指向字符的指针变量做参数,在被调用的函数中可以改变字符串的内容,在主调函数中可以得到改变了的字符串。

    用函数调用实现字符串的复制

    (1)用字符数组作参数

    #include <studio.h>
    void main()
    {
    void copy_string(char from[],char to[]);
    char a[]="i am a teacher.";
    char b[]="you are a student";
    printf("string a=%s string b=%s ",a,b);
    printf("copy string a to string b: ");
    copy_string(a,b);
    printf(" string a=%s string b=%s ",a,b );
    return;
    }

    void copy_string(char from[],char to[])
    {
    int i=0;
    while (from[i]!='')
    {
    to[i]=from[i];
    i++;
    to[i]='';
    }
    }

    >>用字符指针变量作实参,先使指针变量a和b分别指向两个字符串;

    #include <studio.h>
    void main()
    {
    void copy_string(char from[],char to[]);
    char from[]="i am a teacher";
    char to[]="you are a student.";
    char *a=from;
    char *b=to;
    printf("string a=%s string b=%s ",a,b);
    printf("copy string a to string b: ");
    copy_string(a,b);
    printf(" string a=%s string b=%s ",a,b );
    return;
    }
    void copy_string(char from[],char to[])
    {
    int i=0;
    while(from[i]!='')
    to[i]=from[i];
    i++;
    to[i]='';
    }

    >>形参用字符指针变量

    #include <studio.h>
    void main()
    {
    void copy_string(char *from,char *to);
    char from[]="i am a teacher";
    char to[]="you are a student.";
    char *a=from;
    char *b=to;
    printf("string a=%s string b=%s ",a,b);
    printf("copy string a to string b: ");
    copy_string(a,b);
    printf(" string a=%s string b=%s ",a,b );
    return;
    }
    void copy_string(char *from,char *to)
    {
    for (;*from!='';from++;to++)
    {
    *to=*from;
    *to='';
    }
    }

  • 相关阅读:
    为什么lambda中用到的局部变量需要为final
    ubuntu安装idea之后字体不友好
    mysql存表情出错的解决方案(类似xF0x9Fx98x86xF0x9F)
    CentOS7.4 安装mysql
    mysql修改时区
    发个自己写的微信小游戏
    算法:IP分割问题(python实现)
    教你用Python抓取百度翻译
    教你用Python遍历指定目录下的所有文件以及文件的过滤
    教你用Python做个简单的加密程序(还基础什么呀,直接来练习吧,带源码)
  • 原文地址:https://www.cnblogs.com/collect/p/4126427.html
Copyright © 2011-2022 走看看