• 字符串与指针{学习笔记}


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

    #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='';
    }
    }

  • 相关阅读:
    【ROC曲线】关于ROC曲线、PR曲线对于不平衡样本的不敏感性分析说引发的思考
    MathJax测试
    现有C2B模式小总结
    语音识别技术简介
    Spark运行调试方法与学习资源汇总
    [Apache Spark源码阅读]天堂之门——SparkContext解析
    对三维数据集的K-means聚类研究
    根据《关于“k-means算法在流式细胞仪中细胞分类的应用”的学习笔记总结》撰写的中期报告
    关于《k-means算法在流式细胞仪中细胞分类的应用》的学习笔记总结
    用shell脚本自动化安装hadoop
  • 原文地址:https://www.cnblogs.com/collect/p/4126427.html
Copyright © 2020-2023  润新知