大部分程序都要频繁地对字符串进行操作,学过java的小伙伴都知道有一个String类,提供了许多操作字符串(如:字符串分割、截取、拼接等)的函数,在c++的string类对字符串也进行了很强大的封装,方便我们使用。

要想使用标准C++中string类,需要导入std命名空间

using namespace std;

或者

#include <string>
//然后在使用的时候加入std命名空间
std::string str;

string类的构造函数

string(const char *s); //用char字符串s初始化
string(int n,char c); //用n个字符c初始化

例如:

string str1 ("老九学堂");
string str2 (3, '6');

此外,string类还支持默认构造函数和复制构造函数,如string s1;string s2=”hello”;都是正确的写法。当构造的string太长而无法表达时会抛出length_error异常。

string类的字符操作

const char &operator[](int n)const;
const char &at(int n)const;
char &operator[](int n);
char &at(int n);
operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range异常,下标运算符[]不提供检查访问。

例如:

string str = "code and debug";
cout << str[0] << str[1] << endl;
cout << str.at(2) << str.at(3) << endl;

const char *data()const;
const char *c_str()const;
返回指向一个数组的指针,该数组包含一个以空值终止的字符序列(即C字符串),代表字符串对象的当前值。data和c_str都是同义词,并且返回相同的值

例如:

string str = "code and debug";
const char* data = str.data();
const char* cstr = str.c_str();
cout << data << "," << cstr << endl;

int copy(char *s, int n, int pos = 0) const;
把当前串中以pos开始的n个字符拷贝到以s为起始位置的字符数组中,返回实际拷贝的数目

例如:

char buffer[20];
string str("www.xuetang9.com");
size_t length = str.copy(buffer, 6, 5);
buffer[length] = '\0';
cout << "buffer contains: " << buffer << endl;

string的特性描述

int capacity()const;//返回当前容量(即string中不必增加内存即可存放的元素个数)
int max_size()const;//返回string对象中可存放的最大字符串的长度
int size()const; //返回当前字符串的大小
int length()const; //返回当前字符串的长度
bool empty()const; //当前字符串是否为空
例如:

string str("www.xuetang9.com");
cout << "size: " << str.size() << endl;
cout << "length: " << str.length() << endl;
cout << "capacity: " << str.capacity() << endl;
cout << "max_size: " << str.max_size() << endl;
cout << "empty: " << str.empty() << endl;

void resize(int len,char c); //把字符串当前大小置为len,并用字符c填充不足的部分
例如:

string str("code in C");
cout << str << endl;

unsigned sz = str.size();
str.resize(sz + 2, '+');
cout << str << endl;

str.resize(14);
cout << str << endl;

string的赋值

//把字符串s赋给当前字符串
string &operator=(const string &s);
//把字符串s赋给当前字符串
string& assign (const string& str);
//把字符串s中从pos开始的n个字符赋给当前字符串
string& assign (const string& str, size_t pos, size_t n);
//把char类型字符串s赋给当前字符串
string& assign (const char* s);
//把char类型字符串s开始的n个字符赋给当前字符串
string& assign (const char* s, size_t n);
//把n个字符c赋值给当前字符串
string& assign (size_t n, char c);
//把first和last迭代器之间的部分赋给字符串
string& assign (InputIterator first, InputIterator last);
等号赋值这里就不再演示了,下面来演示assign函数的使用

string str;
string base = "The quick brown fox jumps over a lazy dog.";

str.assign(base);
cout << str << endl;

str.assign(base, 10, 9);
cout << str << endl;         // 输出结果:"brown fox"

str.assign("pangrams are cool", 7);
cout << str << endl;         // 输出结果:"pangram"

str.assign("c-string");
cout << str << endl;         // 输出结果:"c-string"

str.assign(10, '*');
cout << str << endl;         // 输出结果:"**********"

str.assign(base.begin() + 16, base.end() - 12);
cout << str << endl;         // 输出结果:"fox jumps over"

string的连接

//把字符串s连接到当前字符串的结尾
string &operator+=(const string &s);
//同operator+=()
string& append (const string& s);
//把字符串s中从pos开始的n个字符连接到当前字符串的结尾
string& append (const string& s, size_t pos, size_t n);
//把char类型字符串s连接到当前字符串结尾
string& append (const char* s);
//把char类型字符串s的前n个字符连接到当前字符串结尾
string& append (const char* s, size_t n);
//在当前字符串结尾添加n个字符c
string& append (size_t n, char c);
//把迭代器first和last之间的部分连接到当前字符串的结尾
string& append (InputIterator first, InputIterator last);
字符串的+号拼接这里就不做演示了,观察append语法,其实与assign差不多,下面来看看

string str;
string str2 = "Writing ";
string str3 = "print 10 and then 5 more";
str.append(str2);                           // 拼接,"Writing "
str.append(str3, 6, 3);                     // 拼接,"10 "
str.append("dots are cool", 5);             // 拼接,"dots "
str.append("here: ");                       // 拼接,"here: "
str.append(10u, '.');                       // 拼接,".........."
str.append(str3.begin() + 8, str3.end());   // 拼接," and then 5 more"
cout << str << endl;

string的比较

//比较两个字符串是否相等
bool operator==(const string &s1,const string &s2)const;
运算符”>”,”=”,”<=","!="均被重载用于字符串的比较
//比较当前字符串和s的大小
int compare(const string &s) const;
//比较当前字符串从pos开始的n个字符组成的字符串与s的大小
int compare(size_t pos, size_t n,const string &s)const;
//比较当前字符串从pos开始的n个字符组成的字符串与s中pos2开始的n2个字符组成的字符串的大小
int compare(size_t pos, size_t n,const string &s,size_t pos2,size_t n2)const;
//下面三个方法用于当前字符与char类型字符串比较大小
int compare(const char *s) const;
int compare(size_t pos, size_t n,const char *s) const;
int compare(size_t pos, size_t n,const char *s, size_t pos2) const;
compare函数在大于时返回1,小于时返回-1,等于时返回0
操作符比较就不作演示了,下面来演示一下compare的用法

string str1("green apple");
string str2("red apple");
if (str1.compare(str2) != 0)
    cout << str1 << " is not " << str2 << endl;
if (str1.compare(6, 5, "apple") == 0)
    cout << "still, " << str1 << " is an apple" << endl;
if (str2.compare(str2.size() - 5, 5, "apple") == 0)
    cout << "and " << str2 << " is also an apple" << endl;
if (str1.compare(6, 5, str2, 4, 5) == 0)
    cout << "therefore, both are apples" << endl;

string的截取

//返回pos开始的n个字符组成的字符串
string substr(size_t pos = 0,size_t n = npos) const;
例如:

string str = "We think in generalities, but we live in details.";
string str2 = str.substr(3, 5);     // "截取think"
size_t pos = str.find("live");      // 查找"live"的位置
string str3 = str.substr(pos);      // 截取从"live"开始到文本结尾的字符串
cout << str2 << ' ' << str3 << endl;

string的交换

//交换当前字符串与s2的值
void swap(string &s2);
例如:

string buyer("money");
string seller("goods");
cout << "Before the swap, buyer has " << buyer;
cout << " and seller has " << seller << endl;
seller.swap(buyer);
cout << " After the swap, buyer has " << buyer;
cout << " and seller has " << seller << endl;

string类的查找函数

//从pos开始查找字符串s在当前串中的位置
size_t find(const string &s, size_t pos = 0) const;
//从pos开始查找字符串s在当前串中的位置
size_t find(const char *s, size_t pos = 0) const;
//从pos开始查找字符串s中前n个字符在当前串中的位置
size_t find(const char *s, size_t pos, size_t n) const;
//从pos开始查找字符c在当前字符串的位置
size_t find(char c, size_t pos = 0) const;
//查找成功时返回所在位置,失败返回string::npos的值
例如:

std::string str("There are two needles in this haystack with needles.");
std::string str2("needle");
std::size_t found = str.find(str2);
if (found != std::string::npos)
    std::cout << "first 'needle' found at: " << found << endl;
found = str.find("needles are small", found + 1, 6);
if (found != std::string::npos)
    std::cout << "second 'needle' found at: " << found << endl;
found = str.find("haystack");
if (found != std::string::npos)
    std::cout << "'haystack' also found at: " << found << endl;
found = str.find('.');
if (found != std::string::npos)
    std::cout << "Period found at: " << found << endl;

//查找字符串中最后出现的指定字符串的位置,如果指定了pos那么只在字符串开始到指定位置查找
size_t rfind(char c, size_t pos = npos) const;
size_t rfind(const char *s, size_t pos = npos) const;
size_t rfind(const char *s, size_t pos, size_t n = npos) const;//n表示匹配字符个数
size_t rfind(const string &s,size_t pos = npos) const;
例如:

std::string str("The sixth sick sheik's sixth sheep's sick.");
std::string key("sixth");
//查找字符串中最后出现"sixth"的位置
std::size_t found = str.rfind(key);
std::cout << found << endl;
//查找字符串中前20个字符位,最后出现"sixth"的位置
found = str.rfind(key, 20);
std::cout << found << endl;
//查找字符串中前9个字符位,最后出现"si"的位置
found = str.rfind("sic", 9, 2);
std::cout << found << endl;

//在字符串中搜索与参数中指定的任何字符匹配的第一个字符,如果指定了pos,则搜索仅包括位置pos或之后的字符,而忽略pos之前可能出现的任何字符。
size_t find_first_of(char c, size_t pos = 0) const;
size_t find_first_of(const char *s, size_t pos = 0) const;
size_t find_first_of(const char *s, size_t pos, size_t n) const;//n表示匹配字符个数
size_t find_first_of(const string &s,size_t pos = 0) const;
例如:

std::string str("hello world");
std::size_t found = str.find_first_of("l");
std::cout << found << endl;
found = str.find_first_of('l');
std::cout << found << endl;
found = str.find_first_of('l',3);
std::cout << found << endl;

//在字符串中搜索与参数中指定的任何字符都不匹配的第一个字符位。如果指定了pos,则搜索仅包括位置pos或之后的字符,而忽略该字符之前的所有可能出现的情况。
size_t find_first_not_of(char c, size_t pos = 0) const;
size_t find_first_not_of(const char *s, size_t pos = 0) const;
size_t find_first_not_of(const char *s, size_t pos,size_t n) const;//n表示匹配字符个数
size_t find_first_not_of(const string &s,size_t pos = 0) const;
例如:

std::string str("look for non-alphabetic characters...");
std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz");
if (found != std::string::npos)
{
    std::cout << "The first non-alphabetic pos is " << found << endl;
}

除了find_first_of和find_first_not_of函数,还有find_last_of和find_last_not_of,它的用法基本一致,只是find_last_of和find_last_not_of,如果指定了pos,则搜索仅包括位置pos或之前的字符,而忽略pos之后的任何可能出现的情况,这里就不再举例说明。

string类的替换函数

//删除从p0开始的n0个字符,然后在p0处插入串s
string &replace(size_t p0, size_t n0,const char *s);
//删除p0开始的n0个字符,然后在p0处插入字符串s的前n个字符
string &replace(size_t p0, size_t n0,const char *s, size_t n);
//删除从p0开始的n0个字符,然后在p0处插入串s
string &replace(size_t p0, size_t n0,const string &s);
//删除p0开始的n0个字符,然后在p0处插入串s中从pos开始的n个字符
string &replace(size_t p0, size_t n0,const string &s, size_t pos, int n);
//删除p0开始的n0个字符,然后在p0处插入n个字符c
string &replace(size_t p0, size_t n0,size_t n, char c);
//把[first0,last0)之间的部分替换为字符串s
string &replace(iterator first0, iterator last0,const char *s);
//把[first0,last0)之间的部分替换为s的前n个字符
string &replace(iterator first0, iterator last0,const char *s, int n);
//把[first0,last0)之间的部分替换为串s
string &replace(iterator first0, iterator last0,const string &s);
//把[first0,last0)之间的部分替换为n个字符c
string &replace(iterator first0, iterator last0,int n, char c);
//把[first0,last0)之间的部分替换成[first,last)之间的字符串
string &replace(iterator first0, iterator last0,const_iterator first, const_iterator last);
例如:

std::string base = "this is a test string.";
std::string str2 = "n example";
std::string str3 = "sample phrase";
std::string str4 = "useful.";
std::string str = base;             // "this is a test string."
str.replace(9, 5, str2);            // "this is an example string." (1)
str.replace(19, 6, str3, 7, 6);     // "this is an example phrase." (2)
str.replace(8, 10, "just a");       // "this is just a phrase."     (3)
str.replace(8, 6, "a shorty", 7);   // "this is a short phrase."    (4)
str.replace(22, 1, 3, '!');         // "this is a short phrase!!!"  (5)
str.replace(str.begin(), str.end() - 3, str3);                      // "sample phrase!!!"      (1)
str.replace(str.begin(), str.begin() + 6, "replace");               // "replace phrase!!!"     (3)
str.replace(str.begin() + 8, str.begin() + 14, "is coolness", 7);   // "replace is cool!!!"    (4)
str.replace(str.begin() + 12, str.end() - 4, 4, 'o');               // "replace is cooool!!!"  (5)
str.replace(str.begin() + 11, str.end(), str4.begin(), str4.end()); // "replace is useful."    (6)
std::cout << str << endl;

字符串流处理

通过定义ostringstream和istringstream变量实现
例如:

//导入头
#include <sstream>
//.......
string input("hello,this is a test");
istringstream is(input);
string s1, s2, s3, s4;
is >> s1 >> s2 >> s3 >> s4;//s1="hello,this",s2="is",s3="a",s4="test"
ostringstream os;
os << s1 << s2 << s3 << s4;
cout << os.str();

以上就是常用的字符串操作函数,当然还有其他函数我们可以通过查询API文档获取更多string操作函数,后面是链接地址:http:///www.cplusplus.com/reference/string/string