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 }

    一切尽在注释中。

  • 相关阅读:
    CSS清浮动
    深入理解BFC
    深入理解CSS浮动
    CSS颜色模式转换器的实现
    深入理解CSS背景
    理解CSS前景色和透明度
    深入理解CSS六种颜色模式
    HTML学习目录
    深入理解display属性
    深入理解盒模型
  • 原文地址:https://www.cnblogs.com/dayq/p/12181961.html
Copyright © 2011-2022 走看看