string转char*
string str=“world”; const char *p = str.c_str();//同上,要加const或者等号右边用char*
char * p=(char*)str.c_str();
string 转char[]
1 string pp = "dagah"; 2 char p[8]; 3 int i; 4 for( i=0;i<pp.length();i++) 5 p[i] = pp[i]; 6 p[i] = '\0'; 7 printf("%s\n",p); 8 cout<<p;
char* 转string
1 string s; 2 char *p = "hello";//直接赋值 3 s = p;
char[] 转string
同上
/
字符串数字互相转换
#include <iostream>#include <sstream>
#include <cstring>
#include <string>
using namespace std;
template<typename inT,typename outT>
outT convert(const inT &in)
{
stringstream stream;
stream<<in;
outT out;
stream>>out;
return out;
}
int main()
{
int a = 8888;
string b;
b= convert<int,string>(a);
cout<<b<<endl;
string aa = "8888";
int bb;
bb= convert<string,int>(aa);
cout<<bb<<endl;
return 0;
}
字符串分割
#include<stdio.h> #include<string.h> int main(void) { char buf[]="hello@boy@this@is@heima"; char*temp = strtok(buf,"@"); while(temp) { printf("%s ",temp); temp = strtok(NULL,"@"); } return 0; }
#include<stdio.h>
#include<string.h>
#include<vector>
#include<string>
#include<iostream>
using namespace std;
int main(void)
{
char buf[]="hello@boy@this@is@heima";
//int len = strlen(buf);
//cout<<len<<endl;
const char* buf1="hello@boy@this@is@heima";
string str = buf1;
char* buf11 = (char*)str.c_str();
vector<string> vs;
char* temp = strtok(buf11,"@");
while(temp)
{
//printf("%s ",temp);
vs.push_back(temp);
temp = strtok(NULL,"@");
}
for(int i=0;i<vs.size();i++)
cout<<vs[i]<<" "<<endl;
return 0;
}
///
set应用
#include<stdio.h>
#include<string.h>
#include<vector>
#include<string>
#include<iostream>
#include<set>
using namespace std;
int main(void)
{
int arr[5] = {4,3,2,1,0};
set<int> si(arr,arr+5);
si.insert(7);
si.insert(4);
si.insert(2);
set<string> ss;
ss.insert("bcdef");
ss.insert("abcd");
set<int>::iterator it = si.begin();
for(it;it!=si.end();it++)
{
cout<<*it<<" ";
}
set<string>::iterator its = ss.begin();
for(its;its!=ss.end();its++)
{
cout<<*its<<" ";
}
return 0;
}
/