C++中string类型与char *类型转换

来源:互联网 发布:蓝牙扫描app安卓源码 编辑:程序博客网 时间:2024/05/21 13:22

1.string类型转换为char *

(1)使用stringstream进行转换

代码为:

#include <iostream>
#include <string>
#include <cstring>
#include <sstream>

using namespace std;
int main(int argc, char *argv[])
{
      stringstream sstr;
      sstr.clear();
      char * ch = new char[1024];
      string s="abcd";
      sstr<<s;
      sstr>>ch;
      cout<<ch<<endl;


      return 0;
}

(2)运用basic_string::c_str转换

1)函数原型:const value_type *c_str( ) const;

2)函数描述:

Converts the contents of a string as a C-style, null-terminated string.

将一个字符串的内容转化为一个c风格字符串的指针。

3)代码为:

 

// basic_string_c_str.cpp// compile with: /EHsc#include <string>#include <iostream>int main( ) {   using namespace std;   string  str1 ( "Hello world" );   cout << "The original string object str1 is: "         << str1 << endl;   cout << "The length of the string object str1 = "         << str1.length ( ) << endl << endl;   // Converting a string to an array of characters   const char *ptr1 = 0;   ptr1= str1.data ( );   cout << "The modified string object ptr1 is: " << ptr1         << endl;   cout << "The length of character array str1 = "         << strlen ( ptr1) << endl << endl;   // Converting a string to a C-style string   const char *c_str1 = str1.c_str ( );   cout << "The C-style string c_str1 is: " << c_str1         << endl;   cout << "The length of C-style string str1 = "         << strlen ( c_str1) << endl << endl;}

4)运行结果:

The original string object str1 is: Hello worldThe length of the string object str1 = 11The modified string object ptr1 is: Hello worldThe length of character array str1 = 11The C-style string c_str1 is: Hello worldThe length of C-style string str1 = 11

2.char *类型转换为字符串string型

#include<iostream>

#include<cstring>

using namespace std;

int main()

{

       string str = "hello world";

       char * ch = 0;

       //one method

       strcpy(ch,str.c_str());    //即可

       cout << ch << endl;

      //another method

       for(int  i = 0; i < str.length();i ++ )

       {

             ch = str.at(i);

             ch++;

       }

//    system("pause");

       return 0;

}

 

 

原创粉丝点击