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 }

    一切尽在注释中。

  • 相关阅读:
    结构型模式:装饰者
    SQL Server Collatation
    实践SQLServer Tuning
    导出jar包时需指定mainclass
    垃圾回收
    web.config的部署
    控制反转与依赖注入
    Design Patterns Refcard
    实践理解计算机启动过程
    备忘录(memento)
  • 原文地址:https://www.cnblogs.com/dayq/p/12181961.html
Copyright © 2011-2022 走看看