string的常用操作

操作符

1.+:可以把两个字符串加起来

插入

1 iterator insert(iterator i, const char &ch);
2 basic_string &insert(size_type index, const basic_string &str);
3 basic_string &insert(size_type index, const char *str);

1.在迭代器i表示的位置前面插入一个字符ch

2.(比较特殊,可以使用下标)在字符串的位置index插入string对象str

3.(比较特殊,可以使用下标)在字符串的位置index插入字符串str

追加

string s1 = "hello";
string s2 = " world";

s1 += s2;//正确,s1的值为”hello world“
s1 += "world";// 正确,s1的值为"hello world"
s1 += 'c'; //正确,s1的值为"helloc"

s1.append(s2);//正确,s1的值为"hello world"
s1.append(" world");//正确,s1的值为"hello world"
s1.append('c');//错误,append函数不支持追加字符

s1.push_back(s2);//错误,push_back只能追加字符
s1.push_back("world");//错误,push_back只能追加字符
s1.push_back('c');//正确

+= :在string对象尾部追加内容,"+="可追加string对象字符以及C风格字符串

append():append函数则可以追加string对象C风格字符串

push_back():push_back函数只能追加字符

删除

1 iterator erase(iterator pos);
2 iterator erase(iterator start, iterator end);
3 basic_string &erase(size_type index = 0, size_type num = npos);

1.删除pos指向的字符, 返回指向下一个字符的迭代器

2.删除从start到end的所有字符,返回一个迭代器,指向被删除的最后一个字符的下一个字符

3.删除从index索引开始的num个字符, 返回*this,index默认值为0,num默认值为npos(字符串总字符个数)

转换为char*

成员函数c_str()函数返回一个指向正规C字符串的指针,内容与本string串相同。

子串

1 string substr (size_t pos = 0, size_t len = npos) const;

 从下标pos开始,长度为len的子串。

将数值转化为string

std::string to_string(int value);
std::string to_string(long value);
std::string to_string(long long value); 
std::string to_string(unsigned value); 
std::string to_string(unsigned long value);
std::string to_string(unsigned long long value);
std::string to_string(float value);
std::string to_string(double value);
std::string to_string(long double value);

to_string函数(c++11):将各种类型的数值转化为string

string转化为char*

1.strdup()函数是c语言中常用的一种字符串拷贝库函数,一般和free()函数成对出现, 头文件:string.h 

函数原型:

char *strdup(const char *s)
{
        char *t = NULL;
        if (s && (t = (char*)malloc(strlen(s) + 1)))
        strcpy(t, s);
        return t;
}  

 使用示例:

int main()
{
    string s = "abb";
    char* cst = strdup(s.c_str());//windows下为_strdup
    free(cst);
    return 0;
}

 2.string::c_str()返回const char*,再使用strcpy()函数转化为char*,char *strcpy(char* dest, const char *src),strcpy把从src地址开始且含有''结束符的字符串复制到以dest开始的地址空间:

string s = "aaabgg";
char* cst = (char*)s.c_str();

3.string::c_str()返回const char*,再使用strcpy()函数转化为char*,char *strcpy(char* dest, const char *src),strcpy把从src地址开始且含有''结束符的字符串复制到以dest开始的地址空间:

string s = "aaabgg";
char cst[10240] = { '' };//等价于char* cst=(char*)malloc(s.size()+1);
strcpy(cst, s.c_str());
原文地址:https://www.cnblogs.com/Joezzz/p/9692013.html