杂项

来源:互联网 发布:java项目开发流程图 编辑:程序博客网 时间:2024/05/21 19:39

常用拼接:

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;



常用拆分:

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

voidTestGetLineWithStringStream()
{
    //1.线程安全的,但是只能以字符作为分隔符
    stringstream ss("google|twitter|facebook|microsoft|apple|ibm|");
    string str;
    while(getline(ss,str,'|'))
    {
        cout << str << endl;
    }
}
 
voidTestStringFind()
{
    //1.自己实现,线程安全,支持字符串作为分隔符.缺点可能就是代码量多.
    string str = "google||twitter||facebook||microsoft||apple||ibm||";
    constchar* delim = "||";
    constint 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;
    }
}







原创粉丝点击