杂项

常用拼接:

char* + int

转换为char*

char* str = "hello";
int a = 10;
char *buffer = new char[strlen(str)+sizeof(a)+1];
sprintf(buffer, "_%s_%d_", str, a);
cout << buffer << endl;

转换为string

string s = "hello";
int a = 10;
s += to_string(a);
cout << s << endl;


转换为string(利用字符串io流)

string s = "hello";

int a = 10;
ostringstream ss;
ss << s << a << endl;
s = ss.str();
cout << s << endl;



常用拆分:

void TestStrtok()
{
     //1.非线程安全的,如果多个线程同时调用,会覆盖掉原来的值.
     //2.支持以字符串分割.
     //3.源字符串必须是可修改的.
     char c_str[]= "google||twitter||facebook||microsoft||apple||ibm||" ;
     const char * delim = "||" ;
     char * result = strtok(c_str,delim);
     while (result != NULL)
     {
         cout << result << endl;
         result = strtok(NULL,delim);
     }
}

void TestGetLineWithStringStream()
{
     //1.线程安全的,但是只能以字符作为分隔符
     stringstream ss( "google|twitter|facebook|microsoft|apple|ibm|" );
     string str;
     while (getline(ss,str, '|' ))
     {
         cout << str << endl;
     }
}
 
void TestStringFind()
{
     //1.自己实现,线程安全,支持字符串作为分隔符.缺点可能就是代码量多.
     string str = "google||twitter||facebook||microsoft||apple||ibm||" ;
     const char * delim = "||" ;
     const int len = strlen(delim);
     size_t index = 0 ;
     size_t pos = str.find(delim,index);
     while (pos != string::npos)
     {
         string ss = str.substr(index,pos-index);
         cout << ss << endl;
         index = pos+len;
         pos = str.find(delim,index);
     }
 
     //cout << "is last?" << " index:" << index << " str.length():" << str.length() << endl;
     if ((index+ 1 ) < str.length())
     {
         string ss = str.substr(index,str.length() - index);
         cout << ss << endl;
     }
}







你可能感兴趣的:(C/C++)