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

  • 相关阅读:
    centos 创建swap 交换分区
    nginx android app 慢网络请求超时
    使用docker toolbox 在windows上搭建统一环境
    Docker Volume 之权限管理(转)
    一次架构失误的反思
    Cannot connect to the Docker daemon. Is the docker daemon running on this host?
    docker-compose启动报错,解决方案
    php 执行程序分析
    继电器是如何成为CPU的(2)
    [每天默写一个算法]KMP
  • 原文地址:https://www.cnblogs.com/collect/p/4126427.html
Copyright © 2011-2022 走看看