zoukankan      html  css  js  c++  java
  • string 与 char* 互转

    一、string转换为char*有3中方法:
    1.data

    string str="good boy";
    const char *p=str.data();

    2.c_str

    string str="good boy";
    const char *p=str.c_str();
    1. copy
    string str="good boy";
    char p[20];
    str.copy(p,5,0); //这里5,代表复制几个字符,0代表复制的位置
    *(p+5)=''; //要手动加上结束符

    或者:

    string str="good boy";
    char *p;
    int len = str.length();
    p=(char *)malloc((len+1)*sizeof(char));
    str.copy(p,len,0);

    二、char*转换为string

    char* s="good boy";
    string str=s;

    或者

    char s[20]="good boy";
    string str=s;

    三、string转换成char[]

    string str = "good boy";
    char p[20];
    for(int i=0;i<str.length();i++)
    p[i] = str[i];
    p[str.length()] = ''; 

    或者

    string str="good boy";
    char p[20];
    str.copy(p,5,0); 
    
    *(p+5)=''; 
  • 相关阅读:
    python--异常处理
    Codeforces 1499D
    Codeforces 1263E
    Codeforces 1493D
    Codeforces 1492D
    Codeforces 1490G
    Codeforces 1487E
    Codeforces 1485D
    Codeforces 1485C
    P6917 [ICPC2016 WF]Balanced Diet
  • 原文地址:https://www.cnblogs.com/laohaozi/p/8266500.html
Copyright © 2011-2022 走看看