zoukankan      html  css  js  c++  java
  • char数组和string的相互转换

     1 //char数组和string的转换 
     2 #include<iostream>
     3 #include<string.h>
     4 using namespace std;
     5 int main()
     6 {
     7     char ch[]="hello world"; 
     8 //    string s=ch;/* string可以直接用char数组赋值*/
     9     string s(ch);/* 对string赋值char数组差不多就这两种*/ 
    10     cout<<"ch="<<ch<<endl;
    11     printf("ch=%s
    ",ch);
    12     cout<<"s="<<s<<endl;/*printf("s=%s",s); string不能直接用printf输出,需要用.c_str()*/
    13     printf("s=%s
    ",s.c_str());
    14     string a="helloworldaaa";
    15     const char *c;
    16     c=a.c_str();
    17     cout<<"c="<<c<<endl;
    18     c=s.c_str();
    19     cout<<"c="<<c<<endl;/* 对const char* 数组赋值,可以用string.c_str()*/
    20     const char *c1;
    21     c1=a.data();/* .data 和.c_str()类似,只是字符串末尾没有了*/
    22     cout<<"c1="<<c1<<endl; 
    23     char c2[100];/* 用strcpy的话,就不能是指针类型,必须给定char数组长度*/
    24     strcpy(c2,a.c_str());
    25     cout<<"c2="<<c2<<endl;
    26 }

    一切尽在注释中。

  • 相关阅读:
    【iOS开发】动态添加子视图 UIView 的正确方法
    70.容器分配ip
    79.scp命令
    78.ssh隧道
    77.手撕sql语句
    76.ssh基于秘钥形式连接
    75.python删除目录
    74.ssh服务介绍(基于密码连接)
    73.nginx跨域
    72.nginx文件配置
  • 原文地址:https://www.cnblogs.com/dayq/p/12181961.html
Copyright © 2011-2022 走看看