C++/C++11中std::string用法汇总
C++/C++11中std::string是个模板类,它是一个标准库。使用string类型必须首先包含<string>头文件。作为标准库的一部分,string定义在命名空间std中。
std::string是C++中的字符串。字符串对象是一种特殊类型的容器,专门设计来操作字符序列。
strings are objects that represent sequences of characters.
The standard string class provides support for such objects with an interface similar to that of a standard container of bytes, but adding features specifically designed to operate with strings of single-byte characters.
The string class is an instantiation of the basic_string class template that uses char (i.e.,bytes) as its character type, with its default char_traits and allocator types.
Note that this class handles bytes independently of the encoding used: If used to handle sequences of multi-byte or variable-length characters (such as UTF-8),all members of this class (such as length or size), as well as its iterators,will still operate in terms of bytes (not actual encoded characters).
一个容器就是一些特定类型对象的集合。顺序容器(sequential container)为程序员提供了控制元素存储和访问顺序的能力。这种顺序不依赖于元素的值,而是与元素加入容器时的位置相对应。
标准库中的顺序容器包括:
(1)、vector:可变大小数组。支持快速随机访问。在尾部之外的位置插入或删除元素可能很慢。
(2)、deque:双端队列。支持快速随机访问。在头尾位置插入/删除速度很快。
(3)、list:双向链表。只支持双向顺序访问。在list中任何位置进行插入/删除操作速度都很快。
(4)、forward_list:单向链表。只支持单向顺序访问。在链表任何位置进行插入/删除操作速度都很快。
(5)、array:固定大小数组。支持快速随机访问。不能添加或删除元素。
(6)、string:与vector相似的容器,但专门用于保存字符。随机访问快。在尾部插入/删除速度快。
除了固定大小的array外,其它容器都提供高效、灵活的内存管理。我们可以添加和删除元素,扩张和收缩容器的大小。容器保存元素的策略对容器操作的效率有着固定的,有时是重大的影响。在某些情况下,存储策略还会影响特定容器是否支持特定操作。
例如,string和vector将元素保存在连续的内存空间中。由于元素是连续存储的,由元素的下标来计算其地址是非常快速的。但是,在这两种容器的中间位置添加或删除元素就会非常耗时:在一次插入或删除操作后,需要移动插入/删除位置之后的所有元素,来保持连续存储。而且,添加一个元素有时可能还需要分配额外的存储空间。在这种情况下,每个元素都必须移动到新的存储空间中。
list和forward_list两个容器的设计目的是令容器任何位置的添加和删除操作都很快速。作为代价,这两个容器不支持元素的随机访问:为了访问一个元素,我们只能遍历整个容器。而且,与vector、deque和array相比,这两个容器的额外内存开销也很大。
deque是一个更为复杂的数据结构。与string和vector类似,deque支持快速的随机访问。与string和vector一样,在deque的中间位置添加或删除元素的代价(可能)很高。但是,在deque的两端添加或删除元素都是很快的,与list或forward_list添加删除元素的速度相当。
forward_list和array是新C++标准增加的类型。与内置数组相比,array是一个种更安全、更容易使用的数组类型。与内置数组类似,array对象的大小是固定的。因此,array不支持添加和删除元素以及改变容器大小的操作。forward_list的设计目标是达到与最好的手写的单向链表数据结构相当的性能。因此,forward_list没有size操作,因为保存或计算其大小就会比手写链表多出额外的开销。对其他容器而言,size保证是一个快速的常量时间的操作。
通常,使用vector是最好的选择,除法你有很好的理由选择其他容器。
以下是一些选择容器的基本原则:
(1)、除法你有很好的理由选择其他容器,否则应该使用vector;
(2)、如果你的程序有很多小的元素,且空间的额外开销很重要,则不要使用list或forward_list;
(3)、如果程序要求随机访问元素,应使用vector或deque;
(4)、如果程序要求在容器的中间插入或删除元素,应使用list或forward_list;
(5)、如果程序需要在头尾位置插入或删除元素,但不会在中间位置进行插入或删除操作,则使用deque;
(6)、如果程序只有在读取输入时才需要在容器中间位置插入元素,随后需要随机访问元素,则:首先,确定是否真的需要在容器中间位置添加元素。当处理输入数据时,通常可以很容器地向vector追加数据,然后再调用标准库的sort函数来重排容器中的元素,从而避免在中间位置添加元素。如果必须在中间位置插入元素,考虑在输入阶段使用list,一旦输入完成,将list中的内容拷贝到一个vector中。
如果你不确定应该使用哪种容器,那么可以在程序中只使用vector和list公共的操作:使用迭代器,不使用下标操作,避免随机访问。这样,在必要时选择使用vector或list都很方便。
一般来说,每个容器都定义在一个头文件中,文件名与类型名相同。即,deque定义在头文件deque中,list定义在头文件list中,以此类推。容器均定义为模板类。
顺序容器几乎可以保存任意类型的元素。特别是,我们可以定义一个容器,其元素的类型是另一个容器。这种容器的定义与任何其他容器类型完全一样:在尖括号中指定元素类型(此种情况下,是另一种容器类型)。typedef basic_string<char, char_traits<char>, allocator<char> > string;
typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> > wstring;
typedef basic_string<char16_t, char_traits<char16_t>, allocator<char16_t> > u16string;
typedef basic_string<char32_t, char_traits<char32_t>, allocator<char32_t> > u32string;
下面的测试代码包含了std::string的所有用法,主要来自 http://www.cplusplus.com/reference/string/string/ 和《C++ Primer(Fifth Edition)》:#include "string.hpp"
#include <string>
#include <iostream>
#include <cctype>
#include <cstddef> // std::size_t
#include <fstream>/*typedef basic_string<char, char_traits<char>, allocator<char> > string;typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> > wstring;typedef basic_string<char16_t, char_traits<char16_t>, allocator<char16_t> > u16string;typedef basic_string<char32_t, char_traits<char32_t>, allocator<char32_t> > u32string;
*/int test_string_init()
{// 如果使用等号(=)初始化一个变量,实际上执行的是拷贝初始化,编译器把等号右侧的初始化拷贝到新创建的对象中去。// 与之相反,如果不使用等号,则执行的是直接初始化std::string s1; // 默认初始化,s1是一个空串std::string s2(s1); // s2是s1的副本std::string s3 = s1; // 等价于s3(s1),s3是s1的副本std::string s4("value"); // s4是字面值"value"的副本,除了字面值最后的那个空字符外,直接初始化std::string s5 = "value"; // 等价于s5("value"),s5是字面值"value"的副本,拷贝初始化std::string s6(10, 'c'); // 把s6初始化为由连续10个字符c组成的串,直接初始化// 对于用多个值进行初始化的情况,非要用拷贝初始化的方式来处理也不是不可以,// 不过需要显示地创建一个(临时)对象用于拷贝std::string s7 = std::string(10, 'c'); // 拷贝初始化,等价于: std::string tmp(10, 'c'); std::string s7 = tmp;// string s(s2, pos2) : s是string s2从下标pos2开始的字符的拷贝,若pos2>s2.size(),构造函数的行为未定义std::string s8(s4, 2);// string s(cp, n) : s是cp指向的数组中前n个字符的拷贝,此数组至少应该包含n个字符char cp[6] {"abcde"};std::string s9(cp, 2);// string s(s2, pos2, len2) : s是string s2从下标pos2开始len2个字符的拷贝。若pos2>s2.size(),构造函数的行为未定义.// 不管len2的值是多少,构造函数至多拷贝s2.size()-pos2个字符std::string s10(s4, 1, 2);return 0;
}int test_string_base()
{int num{ 0 };std::cin >> num;switch (num) {case 0: {// 读写string对象std::string s1;std::cin >> s1; // 将string对象读入s1,遇到空白停止, string对象会自动忽然开头的空白(即空格符、换行符、制表符等)// 并从第一个真正的字符开始读起,直到遇见下一个空白为止std::cout << s1 << std::endl; // 输出s1;std::string s2, s3;std::cin >> s2 >> s3; // 多个输入或多个输出可以连写在一起std::cout << s2 << s3 << std::endl;}break;case 1: {// 读取未知数量的string对象std::string s4;while (std::cin >> s4) { // 反复读取,直至到达文件末尾(ctrl+z)std::cout << s4 << std::endl; // 逐个输出单词,每个单词后面紧跟一个换行}}break;case 2: {// 使用getline读取一整行,getline只要一遇到换行符就结束读取操作并返回结果std::string s5;while (std::getline(std::cin, s5)) { // 按ctrl+z退出循环std::cout << s5 << std::endl; // 触发getline函数返回的那个换行符实际上被丢弃掉了,// 得到的string对象中并不包含该换行符}}break;case 3: {// empty:是否为空返回一个对应的布尔值// 每次读入一整行,遇到空行直接跳过std::string s6;while (std::getline(std::cin, s6)) {if (!s6.empty())std::cout << s6 << std::endl;elsestd::cout << "it is empty" << std::endl;}}break;case 4: {// size: 返回string对象的长度(即string对象中字符的个数)std::string s7;while (std::getline(std::cin, s7)) {auto len = s7.size(); // size函数返回的是一个std::string::size_type类型的值,// 它是一个无符号类型的值,而且能足够存放下任何string对象的大小,std::cout << "string size: " << len << std::endl;}}break;case 5: {// 比较string对象:大小写敏感:==、!=、<、<=、>、>=std::string s1{ "hello" }, s2{ "Hello" }, s3{"Hello world"};if (s1 > s2)std::cout << "s1 > s2" << std::endl;else if (s1 == s2)std::cout << "s1 == s2" << std::endl;else if (s1 < s2)std::cout << "s1 < s2" << std::endl;if (s2 <= s3)std::cout << "s2 <= s3" << std::endl;}break;case 6: {// +: 其内容是把左侧的运算对象与右侧的运算对象串接std::string s1{ "hello, " }, s2{ "world" }, s3;s3 = s1 + s2;std::cout << "s3: " << s3 << std::endl;// 当把string对象和字符字面值及字符串字面值混在一条语句中使用时,// 必须确保每个加法运算符(+)的两侧的对象至少有一个是string,// 不能把字面值直接相加// Note: 字符串字面值与string是不同的类型std::string s4{ "csdn blog" }, s5{ "http://blog.csdn.net/" }, s6;s6 = s4 + ": " + s5 + "fengbingchun";std::cout << s6 << std::endl;}break;case 7: {// substr: 返回一个string,它是原始string的一部分或全部的拷贝,// 可以传递给substr一个可选的开始位置和计数值std::string s{ "hello world" };std::string s2 = s.substr(0, 5); // s2 = hellostd::string s3 = s.substr(6); // s3 = worldstd::string s4 = s.substr(6, 11); // s3 = world//std::string s5 = s.substr(12); // 抛出一个out_of_range异常fprintf(stderr, "s2: %s; s3: %s; s4: %s\n", s2.c_str(), s3.c_str(), s4.c_str());// insert、erase、assigns.insert(s.size(), 5, '!'); // 在s末尾插入5个感叹号fprintf(stdout, "s: %s\n", s.c_str());s.erase(s.size() - 5, 5); // 从s删除最后5个字符fprintf(stdout, "s: %s\n", s.c_str());const char* cp = "Stately, plump Buck";s.assign(cp, 7); // s = "Stately"fprintf(stdout, "s: %s\n", s.c_str());s.insert(s.size(), cp + 7); // s = "Stately, plump Buck"fprintf(stdout, "s: %s\n", s.c_str());std::string s5{ " some string " }, s6{ " some other string " };s5.insert(0, s6); // 在s5中位置0之前插入s6的拷贝fprintf(stdout, "s5: %s\n", s5.c_str());s5.insert(0, s6, 0, s6.size()); // 在s5[0]之前插入s6中s6[0]开始的s6.size()个字符fprintf(stdout, "s5: %s\n", s5.c_str());// append: 是在末尾进行插入操作的一种简写形式std::string s7{ "C++ Primer" }, s8{ s7 };s7.insert(s7.size(), " 5th Ed.");s8.append(" 5th Ed.");fprintf(stdout, "s7: %s; s8: %s\n", s7.c_str(), s8.c_str());// replace: 是调用erase和insert的一种简写形式s7.replace(11, 3, "Fifth"); // s7.erase(11, 3); s7.insert(11, "Fifth");fprintf(stdout, "s7: %s\n", s7.c_str());/*s.find(args):查找s中args第一次出现的位置s.rfind(args):查找s中args最后一次出现的位置s.find_first_of(args):在s中查找args中任何一个字符第一次出现的位置s.find_last_of(args):在s中查找args中任何一个字符最后一次出现的位置s.find_first_not_of(args):在s中查找第一个不在args中的字符s.find_last_not_of(args):在s中查找最后一个不在args中的字符*/// find: 返回第一个匹配位置的下标std::string s9{ "AnnaBelle" };auto pos1 = s9.find("Belle");auto pos2 = s9.find("xxx");fprintf(stdout, "pos1: %d, pos2: %d\n", pos1, pos2); // 4, -1// find_first_of: 查找与给定字符串中任何一个字符匹配的位置std::string numbers{ "0123456789" }, name{ "r2d2" };auto pos3 = name.find_first_of(numbers);fprintf(stdout, "pos3: %d\n", pos3); // 1, name中第一个数字的下标// find_first_not_of: 第一个不在参数中的字符std::string s10{ "03714p3" };auto pos4 = s10.find_first_not_of(numbers);fprintf(stdout, "pos4: %d\n", pos4); // 5// compare: 返回0(等于)、正数(大于)或负数(小于)auto ret = numbers.compare(name);fprintf(stdout, "compare result: %d\n", ret);// -1// 数值数据与string之间的转换int i{ 43 };std::string s11 = std::to_string(i); // 将整数i转换为字符表示形式double d = std::stod(s11); // 将字符串s11转换为浮点数fprintf(stdout, "s11: %s, d: %f\n", s11.c_str(), d);/*to_string(val):一组重载函数,返回数值val的string表示。val可以是任何算术类型stoi(s,p,b)/stol(s,p,b)/stoul(s,p,b)/stoll(s,p,b)/stoull(s,p,b):返回s的起始子串(表示整数内容)的数值,返回类型分别是int、long、unsigned long、long long、unsigned long long。b表示转换所用的基数,默认值为10.p是size_t指针,用来保存s中第一个非数值字符的下标,p默认是0,即,函数不保存下标。stof(s,p)/stod(s,p)/stold(s,p):返回s的起始子串(表示浮点数内容)的数值,返回值类型分别是float、double或long double.参数p的作用与整数转换函数中一样。*/}break;default:break;}return 0;
}int test_string_cctype()
{/* include <cctype>isalnum(c):当c是字母或数字时为真isalpha(c):当c是字母时为真isblank(c):当c是空白字符时为真(C++11)iscntrl(c):当c时控制字符时为真isdigit(c):当c是数字时为真isgraph(c):当c不是空格但可打印时为真islower(c):当c是小写字母时为真isprint(c):当c是可打印字符时为真(即c是空格或c具有可视形式)ispunct(c):当c是标点符号时为真(即c不是控制字符、数字、字母、可打印空白中的一种)isspace(c):当c是空白时为真(即c是空格、横向制表符、纵向制表符、回车符、换行符、进纸符中的一种)isupper(c):当c是大写字母时为真isxdigit(c):当c是十六进制数字时为真tolower(c):如果c是大写字母,输出对应的小写字母;否则原样输出ctoupper(c):如果c是小写字母,输出对应的大写字母;否则原样输出c*/std::string s1{ "Hello World!!!" };decltype(s1.size()) punct_cnt{ 0 };for (auto c : s1) {if (ispunct(c))++punct_cnt;}std::cout << punct_cnt << " punctutation characters in " << s1 << std::endl;for (auto &c : s1) { // 对于s1中的每个字符(Note:c是引用)c = toupper(c); // c是一个引用,因此赋值语句将改变s中字符的值}std::cout << "toupper s1: " << s1 << std::endl;// string对象的下标必须大于等于0而小于s.size()// Note:C++标准并不要求标准库检测下标是否合法。一旦使用了一个超出范围的下标,就会产生不可预知的结果std::string s2{"some string"};for (decltype(s2.size()) index = 0; index != s2.size() && !isspace(s2[index]); ++index) {s2[index] = toupper(s2[index]);}std::cout << "s2: " << s2 << std::endl;// 使用下标执行随机访问const std::string s3{"0123456789ABCDEF"};std::cout << "Enter a series of numbers between 0 and 15"<< "separated by spaces. Hit ENTER when finished: " << std::endl;std::string result;std::string::size_type n;while (std::cin >> n) {if (n < s3.size())result += s3[n];std::cout << "Your hex number is: " << result << std::endl;}return 0;
}static void SplitFilename(const std::string& str)
{std::cout << "Splitting: " << str << '\n';std::size_t found = str.find_last_of("/\\");std::cout << " path: " << str.substr(0, found) << '\n';std::cout << " file: " << str.substr(found + 1) << '\n';
}int test_string_func()
{// reference: http://www.cplusplus.com/reference/string/string/{ // appendstd::string str;std::string str2 = "Writing ";std::string str3 = "print 10 and then 5 more";// used in the same order as described above: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"str.append(5, 0x2E); // "....."std::cout << str << '\n';}{ // assignstd::string str;std::string base = "The quick brown fox jumps over a lazy dog.";// used in the same order as described above:str.assign(base);std::cout << str << '\n';str.assign(base, 10, 9);std::cout << str << '\n'; // "brown fox"str.assign("pangrams are cool", 7);std::cout << str << '\n'; // "pangram"str.assign("c-string");std::cout << str << '\n'; // "c-string"str.assign(10, '*');std::cout << str << '\n'; // "**********"str.assign(10, 0x2D);std::cout << str << '\n'; // "----------"str.assign(base.begin() + 16, base.end() - 12);std::cout << str << '\n'; // "fox jumps over"
}{ // atstd::string str("Test string");for (unsigned i = 0; i<str.length(); ++i) {std::cout << str.at(i);}std::cout << '\n';}{ // back(c++11)std::string str("hello world.");str.back() = '!';std::cout << str << '\n';}{ // begin/endstd::string str("Test string");for (std::string::iterator it = str.begin(); it != str.end(); ++it)std::cout << *it;std::cout << '\n';}{ // capacitystd::string str("Test string");std::cout << "size: " << str.size() << "\n";std::cout << "length: " << str.length() << "\n";std::cout << "capacity: " << str.capacity() << "\n";std::cout << "max_size: " << str.max_size() << "\n";}{ // cbegin/cend(c++11)std::string str("Lorem ipsum");for (auto it = str.cbegin(); it != str.cend(); ++it)std::cout << *it;std::cout << '\n';}{ // clearchar c;std::string str;std::cout << "Please type some lines of text. Enter a dot (.) to finish:\n";do {c = std::cin.get();str += c;if (c == '\n') {std::cout << str;str.clear();}} while (c != '.');}{ // comparestd::string str1("green apple");std::string str2("red apple");if (str1.compare(str2) != 0)std::cout << str1 << " is not " << str2 << '\n';if (str1.compare(6, 5, "apple") == 0)std::cout << "still, " << str1 << " is an apple\n";if (str2.compare(str2.size() - 5, 5, "apple") == 0)std::cout << "and " << str2 << " is also an apple\n";if (str1.compare(6, 5, str2, 4, 5) == 0)std::cout << "therefore, both are apples\n";}{ // copychar buffer[20];std::string str("Test string...");std::size_t length = str.copy(buffer, 6, 5);buffer[length] = '\0';std::cout << "buffer contains: " << buffer << '\n';}{ // crbegin/crend(c++11)std::string str("lorem ipsum");for (auto rit = str.crbegin(); rit != str.crend(); ++rit)std::cout << *rit;std::cout << '\n';}{ // c_strstd::string str("Please split this sentence into tokens");char * cstr = new char[str.length() + 1];std::strcpy(cstr, str.c_str());// cstr now contains a c-string copy of strchar * p = std::strtok(cstr, " ");while (p != 0) {std::cout << p << '\n';p = std::strtok(NULL, " ");}delete[] cstr;}{ // dataint length;std::string str = "Test string";char* cstr = "Test string";if (str.length() == std::strlen(cstr)) {std::cout << "str and cstr have the same length.\n";if (memcmp(cstr, str.data(), str.length()) == 0)std::cout << "str and cstr have the same content.\n";}}{ // emptystd::string content;std::string line;std::cout << "Please introduce a text. Enter an empty line to finish:\n";do {getline(std::cin, line);content += line + '\n';} while (!line.empty());std::cout << "The text you introduced was:\n" << content;}{ // erasestd::string str("This is an example sentence.");std::cout << str << '\n';// "This is an example sentence."str.erase(10, 8); // ^^^^^^^^std::cout << str << '\n';// "This is an sentence."str.erase(str.begin() + 9); // ^std::cout << str << '\n';// "This is a sentence."str.erase(str.begin() + 5, str.end() - 9); // ^^^^^std::cout << str << '\n';// "This sentence."}{ // findstd::string str("There are two needles in this haystack with needles.");std::string str2("needle");// different member versions of find in the same order as above:std::size_t found = str.find(str2);if (found != std::string::npos)std::cout << "first 'needle' found at: " << found << '\n';found = str.find("needles are small", found + 1, 6);if (found != std::string::npos)std::cout << "second 'needle' found at: " << found << '\n';found = str.find("haystack");if (found != std::string::npos)std::cout << "'haystack' also found at: " << found << '\n';found = str.find('.');if (found != std::string::npos)std::cout << "Period found at: " << found << '\n';// let's replace the first needle:str.replace(str.find(str2), str2.length(), "preposition");std::cout << str << '\n';}{ // find_first_not_ofstd::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 character is " << str[found];std::cout << " at position " << found << '\n';}}{ // find_first_ofstd::string str("Please, replace the vowels in this sentence by asterisks.");std::size_t found = str.find_first_of("aeiou");while (found != std::string::npos) {str[found] = '*';found = str.find_first_of("aeiou", found + 1);}std::cout << str << '\n';}{ // find_last_not_ofstd::string str("Please, erase trailing white-spaces \n");std::string whitespaces(" \t\f\v\n\r");std::size_t found = str.find_last_not_of(whitespaces);if (found != std::string::npos)str.erase(found + 1);elsestr.clear(); // str is all whitespacestd::cout << '[' << str << "]\n";}{ // find_last_ofstd::string str1("/usr/bin/man");std::string str2("c:\\windows\\winhelp.exe");SplitFilename(str1);SplitFilename(str2);}{ // front(c++11)std::string str("test string");str.front() = 'T';std::cout << str << '\n';}{ // get_allocator// reference: http://www.tenouk.com/cpluscodesnippet/cplusbasic_stringget_allocator.html// using the default allocatorstd::string str1 = "1234";std::basic_string <char> str2 = "567ABC";std::basic_string <char, std::char_traits<char>, std::allocator<char> > str3 = "DefauLt";std::cout << "str1 = " << str1 << std::endl;std::cout << "str2 = " << str2 << std::endl;std::cout << "str3 = " << str3 << std::endl;// str4 will use the same allocator class as str1std::basic_string <char> str4(str1.get_allocator());std::basic_string <char>::allocator_type xchar = str1.get_allocator();str4 = "Just a string";std::cout << "str4 = " << str4 << std::endl;if (xchar == str1.get_allocator())std::cout << "The allocator objects xchar and str1.get_allocator() are equal." << std::endl;elsestd::cout << "The allocator objects xchar and str1.get_allocator() are not equal." << std::endl;// you can now call functions on the allocator class xchar used by str1std::string str5(xchar);}{ // insertstd::string str = "to be question";std::string str2 = "the ";std::string str3 = "or not to be";std::string::iterator it;// used in the same order as described above:str.insert(6, str2); // to be (the )questionstr.insert(6, str3, 3, 4); // to be (not )the questionstr.insert(10, "that is cool", 8); // to be not (that is )the questionstr.insert(10, "to be "); // to be not (to be )that is the questionstr.insert(15, 1, ':'); // to be not to be(:) that is the questionit = str.insert(str.begin() + 5, ','); // to be(,) not to be: that is the questionstr.insert(str.end(), 3, '.'); // to be, not to be: that is the question(...)str.insert(it + 2, str3.begin(), str3.begin() + 3); // (or )std::cout << str << '\n';}{ // lengthstd::string str("Test string");std::cout << "The size of str is " << str.length() << " bytes.\n";}{ // max_sizestd::string str("Test string");std::cout << "size: " << str.size() << "\n";std::cout << "length: " << str.length() << "\n";std::cout << "capacity: " << str.capacity() << "\n";std::cout << "max_size: " << str.max_size() << "\n";}{ // operator +=std::string name("John");std::string family("Smith");name += " K. "; // c-stringname += family; // stringname += '\n'; // characterstd::cout << name;}{ // operator =std::string str1, str2, str3;str1 = "Test string: "; // c-stringstr2 = 'x'; // single characterstr3 = str1 + str2; // stringstd::cout << str3 << '\n';}{ // operator []std::string str("Test string");for (int i = 0; i<str.length(); ++i) {std::cout << str[i];}}{ // pop_back(c++11)std::string str("hello world!");str.pop_back();std::cout << str << '\n';}{ // push_backstd::string str;std::ifstream file("test.txt", std::ios::in);if (file) {while (!file.eof()) str.push_back(file.get());}std::cout << str << '\n';}{ // rbegin/rendstd::string str("now step live...");for (std::string::reverse_iterator rit = str.rbegin(); rit != str.rend(); ++rit)std::cout << *rit;}{ // replacestd::string base = "this is a test string.";std::string str2 = "n example";std::string str3 = "sample phrase";std::string str4 = "useful.";// replace signatures used in the same order as described above:// Using positions: 0123456789*123456789*12345std::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)// Using iterators: 0123456789*123456789*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 << '\n';}{ // reservestd::string str;std::ifstream file("test.txt", std::ios::in | std::ios::ate);if (file) {std::ifstream::streampos filesize = file.tellg();str.reserve(filesize);file.seekg(0);while (!file.eof()) {str += file.get();}std::cout << str;}}{ // resizestd::string str("I like to code in C");std::cout << str << '\n';unsigned sz = str.size();str.resize(sz + 2, '+');std::cout << str << '\n';str.resize(14);std::cout << str << '\n';}{ // rfindstd::string str("The sixth sick sheik's sixth sheep's sick.");std::string key("sixth");std::size_t found = str.rfind(key);if (found != std::string::npos)str.replace(found, key.length(), "seventh");std::cout << str << '\n';}{ // shrink_to_fit(c++11)std::string str(100, 'x');std::cout << "1. capacity of str: " << str.capacity() << '\n';str.resize(10);std::cout << "2. capacity of str: " << str.capacity() << '\n';str.shrink_to_fit();std::cout << "3. capacity of str: " << str.capacity() << '\n';}{ // sizestd::string str("Test string");std::cout << "The size of str is " << str.size() << " bytes.\n";}{ // substrstd::string str = "We think in generalities, but we live in details.";// (quoting Alfred N. Whitehead)std::string str2 = str.substr(3, 5); // "think"std::size_t pos = str.find("live"); // position of "live" in strstd::string str3 = str.substr(pos); // get from "live" to the endstd::cout << str2 << ' ' << str3 << '\n';}{ // swapstd::string buyer("money");std::string seller("goods");std::cout << "Before the swap, buyer has " << buyer;std::cout << " and seller has " << seller << '\n';seller.swap(buyer);std::cout << " After the swap, buyer has " << buyer;std::cout << " and seller has " << seller << '\n';}{ // npos/*std::string::npos : public static member constantstatic const size_t npos = -1;npos is a static member constant value with the greatest possible value for an element of type size_t.This constant is defined with a value of -1, which because size_t is an unsigned integral type,it is the largest possible representable value for this type.*/}{ // getlinestd::string name;std::cout << "Please, enter your full name: ";std::getline(std::cin, name);std::cout << "Hello, " << name << "!\n";}{ // operator +std::string firstlevel("com");std::string secondlevel("cplusplus");std::string scheme("http://");std::string hostname;std::string url;hostname = "www." + secondlevel + '.' + firstlevel;url = scheme + hostname;std::cout << url << '\n';}{ // operator <<std::string str = "Hello world!";std::cout << str << '\n';}{ // operator >>std::string name;std::cout << "Please, enter your name: ";std::cin >> name;std::cout << "Hello, " << name << "!\n";}{ // string comparisonsstd::string foo = "alpha";std::string bar = "beta";if (foo == bar) std::cout << "foo and bar are equal\n";if (foo != bar) std::cout << "foo and bar are not equal\n";if (foo< bar) std::cout << "foo is less than bar\n";if (foo> bar) std::cout << "foo is greater than bar\n";if (foo <= bar) std::cout << "foo is less than or equal to bar\n";if (foo >= bar) std::cout << "foo is greater than or equal to bar\n";}{ // swap stringsstd::string buyer("money");std::string seller("goods");std::cout << "Before the swap, buyer has " << buyer;std::cout << " and seller has " << seller << '\n';swap(buyer, seller);std::cout << " After the swap, buyer has " << buyer;std::cout << " and seller has " << seller << '\n';}{ // stod(c++11)std::string orbits("365.24 29.53");std::string::size_type sz; // alias of size_tdouble earth = std::stod(orbits, &sz);double moon = std::stod(orbits.substr(sz));std::cout << "The moon completes " << (earth / moon) << " orbits per Earth year.\n";}{ // stof(c++11)std::string orbits("686.97 365.24");std::string::size_type sz; // alias of size_tfloat mars = std::stof(orbits, &sz);float earth = std::stof(orbits.substr(sz));std::cout << "One martian year takes " << (mars / earth) << " Earth years.\n";}{ // stoi(c++11)std::string str_dec = "2001, A Space Odyssey";std::string str_hex = "40c3";std::string str_bin = "-10010110001";std::string str_auto = "0x7f";std::string::size_type sz; // alias of size_tint i_dec = std::stoi(str_dec, &sz);int i_hex = std::stoi(str_hex, nullptr, 16);int i_bin = std::stoi(str_bin, nullptr, 2);int i_auto = std::stoi(str_auto, nullptr, 0);std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";std::cout << str_hex << ": " << i_hex << '\n';std::cout << str_bin << ": " << i_bin << '\n';std::cout << str_auto << ": " << i_auto << '\n';}{ // stol(c++11)std::string str_dec = "1987520";std::string str_hex = "2f04e009";std::string str_bin = "-11101001100100111010";std::string str_auto = "0x7fffff";std::string::size_type sz; // alias of size_tlong li_dec = std::stol(str_dec, &sz);long li_hex = std::stol(str_hex, nullptr, 16);long li_bin = std::stol(str_bin, nullptr, 2);long li_auto = std::stol(str_auto, nullptr, 0);std::cout << str_dec << ": " << li_dec << '\n';std::cout << str_hex << ": " << li_hex << '\n';std::cout << str_bin << ": " << li_bin << '\n';std::cout << str_auto << ": " << li_auto << '\n';}{ // stold(c++11)std::string orbits("90613.305 365.24");std::string::size_type sz; // alias of size_tlong double pluto = std::stod(orbits, &sz);long double earth = std::stod(orbits.substr(sz));std::cout << "Pluto takes " << (pluto / earth) << " years to complete an orbit.\n";}{ // stoll(c++11)std::string str = "8246821 0xffff 020";std::string::size_type sz = 0; // alias of size_twhile (!str.empty()) {long long ll = std::stoll(str, &sz, 0);std::cout << str.substr(0, sz) << " interpreted as " << ll << '\n';str = str.substr(sz);}}{ // stoul(c++11)std::string str{ "1111" };//std::cout << "Enter an unsigned number: ";//std::getline(std::cin, str);unsigned long ul = std::stoul(str, nullptr, 0);std::cout << "You entered: " << ul << '\n';}{ // stoull(c++11)std::string str = "8246821 0xffff 020 -1";std::string::size_type sz = 0; // alias of size_twhile (!str.empty()) {unsigned long long ull = std::stoull(str, &sz, 0);std::cout << str.substr(0, sz) << " interpreted as " << ull << '\n';str = str.substr(sz);}}{ // to_string(c++11)/*string to_string (int val);string to_string (long val);string to_string (long long val);string to_string (unsigned val);string to_string (unsigned long val);string to_string (unsigned long long val);string to_string (float val);string to_string (double val);string to_string (long double val);*/std::string pi = "pi is " + std::to_string(3.1415926);std::string perfect = std::to_string(1 + 2 + 4 + 7 + 14) + " is a perfect number";std::cout << pi << '\n';std::cout << perfect << '\n';}{ // to_wstring(c++11)/*wstring to_wstring (int val);wstring to_wstring (long val);wstring to_wstring (long long val);wstring to_wstring (unsigned val);wstring to_wstring (unsigned long val);wstring to_wstring (unsigned long long val);wstring to_wstring (float val);wstring to_wstring (double val);wstring to_wstring (long double val);*/std::wstring pi = L"pi is " + std::to_wstring(3.1415926);std::wstring perfect = std::to_wstring(1 + 2 + 4 + 7 + 14) + L" is a perfect number";std::wcout << pi << L'\n';std::wcout << perfect << L'\n';}return 0;
}int test_string_ifstream_to_string()
{// reference: http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstringstd::ifstream file("E:/GitCode/Messy_Test/testdata/regex.txt");if (!file) {fprintf(stderr, "read file failed!\n");return -1;}std::string str((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());fprintf(stderr, "file content: \n%s\n", str.c_str());return 0;
}
GitHub: https://github.com/fengbingchun/Messy_Test
相关文章:

你在付费听《说好不哭》,我在这里免费看直播还送书 | CSDN新书发布会
周一的时候,我拖着疲惫的身体回到家中,躺倒床上刷刷朋友圈,什么?周杰伦出新歌了?朋友圈都是在分享周杰伦的新歌《说好不哭》,作为周杰伦的粉丝,我赶紧打开手机上的QQ音乐,准备去听&a…

解决Mysql:unrecognized service错误的方法(CentOS)附:修改用户名密码
2019独角兽企业重金招聘Python工程师标准>>> service mysql start出错,mysql启动不了,解决mysql: unrecognized service错误的方法如下: [rootctohome.com ~]# service mysql startmysql: unrecognized service [rootctohome.co…
Caffe源码中Net文件分析
Caffe源码(caffe version commit: 09868ac , date: 2015.08.15)中有一些重要的头文件,这里介绍下include/caffe/net.hpp文件的内容:1. include文件:(1)、<caffe/blob.hpp>:此文件的介绍可以参考:http://blo…

满满干货的硬核技术沙龙,免费看直播还送书 | CSDN新书发布会
周一的时候,我拖着疲惫的身体回到家中,躺倒床上刷刷朋友圈,什么,周杰伦出新歌了?朋友圈都是在分享周杰伦的新歌《说好的不哭》,作为周杰伦的粉丝,我赶紧打开我手机上的QQ音乐,准备去…

【重磅上线】思维导图工具XMind:ZEN基础问题详解合集
XMind是XMind Ltd公司旗下一款出色的思维导图和头脑风暴软件。黑暗的UI设计、独特的ZEN模式、丰富的风格和主题、多分支的颜色等等功能会让你的工作更加便捷与高效。在视觉感官上也会给你带来最佳的体验感。 对于初学者来说,肯定会遇到各种各样的问题,有…

Linux内置的审计跟踪工具:last命令
这个命令是last。它对于追踪非常有用。让我们来看一下last可以为你做些什么。last命令的功能是什么last显示的是自/var/log/wtmp文件创建起所有登录(和登出)的用户。这个文件是二进制文件,它不能被文本编辑器浏览,比如vi、Joe或者其他软件。这是非常有用…

C++/C++11中std::set用法汇总
一个容器就是一些特定类型对象的集合。顺序容器(sequential container)为程序员提供了控制元素存储和访问顺序的能力。这种顺序不依赖于元素的值,而是与元素加入容器时的位置相对应。与之相对的,有序和无序关联容器,则根据关键字的值来存储元…

值得收藏!基于激光雷达数据的深度学习目标检测方法大合集(下)
作者 | 黄浴来源 | 转载自知乎专栏自动驾驶的挑战和发展【导读】在近日发布的《值得收藏!基于激光雷达数据的深度学习目标检测方法大合集(上)》一文中,作者介绍了一部分各大公司和机构基于激光雷达的目标检测所做的工作࿰…

java B2B2C源码电子商务平台 -commonservice-config配置服务搭建
2019独角兽企业重金招聘Python工程师标准>>> Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持。使用Config Server,您可以在所有环境中管理应用程序的外部属性。客户端和服务器上的概念映射与Spring Environment和PropertySource抽象…

Topshelf:一款非常好用的 Windows 服务开发框架
背景 多数系统都会涉及到“后台服务”的开发,一般是为了调度一些自动执行的任务或从队列中消费一些消息,开发 windows service 有一点不爽的是:调试麻烦,当然你还需要知道 windows service 相关的一些开发知识(也不难&…

C++中nothrow的介绍及使用
在C中,使用malloc等分配内存的函数时,一定要检查其返回值是否为”空指针”,并以此作为检查内存操作是否成功的依据,这种Test-for-NULL代码形式是一种良好的编程习惯,也是编写可靠程序所必需的。在C中new在申请内存失败…

你猜猜typeof (typeof 1) 会返回什么值(类型)?!
typeof typeof操作符返回一个字符串,表示未经计算的操作数的类型。 语法: var num a; console.log(typeof (num)); 或console.log(typeof num) 复制代码typeof 可以返回的类型为:number、string、boolean、undefined、null、object、functi…

阿里云智能运维的自动化三剑客
整理 | 王银出品 | AI科技大本营(ID:rgznai100)近日,2019 AI开发者大会在北京举行。会上,近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者进行技术解读和产业论证。而在AIDevOps论坛上,阿里巴巴高级技术专家滕圣…

Sublime Text2.0.2注册码
直接输入注册码就可以了 ----- BEGIN LICENSE ----- Andrew Weber Single User License EA7E-855605 813A03DD 5E4AD9E6 6C0EEB94 BC99798F 942194A6 02396E98 E62C9979 4BB979FE 91424C9D A45400BF F6747D88 2FB88078 90F5CC94 1CDC92DC 8457107A F151657B 1D22E383 A997F016 …
Caffe源码中Solver文件分析
Caffe源码(caffe version commit: 09868ac , date: 2015.08.15)中有一些重要的头文件,这里介绍下include/caffe/solver.hpp文件的内容:1. include文件: <caffe/solver.hpp>:此文件的介绍可以参考: http://b…

百度大脑金秋九月CV盛典,人脸识别新产品及伙伴计划发布会压轴开启
提起人脸识别你最先想到的是什么?是告别排队,刷脸就能支付的超市;还是告别黄牛,刷脸就能自助挂号建档的医院?其实,“刷脸”的时代早已到来,并且人脸识别技术的发展已经超越你的想象,…

BIML 101 - ETL数据清洗 系列 - BIML 快速入门教程 - 序
BIML 101 - BIML 快速入门教程 做大数据的项目,最花时间的就是数据清洗。 没有一个相对可靠的数据,数据分析就是无木之舟,无水之源。 如果你已经进了ETL这个坑,而且预算有限,并且有大量的活要做; 时间紧&am…

ADO数据库操作
void CSjtestDlg::OnBnClickedButtonAdd() {// TODO: 在此添加控件通知处理程序代码this->ShowWindow(SW_HIDE);DigAdd dig ;dig.DoModal() ;this->ShowWindow(SW_SHOW);m_Grid.DeleteAllItems() ;ADOConn m_Adoconn ;m_Adoconn.OnInitADOConn() ;CString sql ;sql.Forma…
C++中try/catch/throw的使用
C异常是指在程序运行时发生的反常行为,这些行为超出了函数正常功能的范围。当程序的某部分检测到一个它无法处理的问题时,需要用到异常处理。异常提供了一种转移程序控制权的方式。C异常处理涉及到三个关键字:try、catch、throw。 在C语言中…

掌握这些步骤,机器学习模型问题药到病除
作者 | Cecelia Shao编译 | ronghuaiyang来源 | AI公园(ID:AI_Paradise)【导读】这篇文章提供了切实可行的步骤来识别和修复机器学习模型的训练、泛化和优化问题。众所周知,调试机器学习代码非常困难。即使对于简单的前馈神经网络也是这样&am…

How to list/dump dm thin pool metadata device?
2019独角兽企业重金招聘Python工程师标准>>> See: How to create metadata-snap for thin tools using? I dont think LVM provides any support for metadata snapshots so you will need to drive this process through dmsetup. The kernel interface is descri…

Linux基础(二)--基础的命令ls和date的详细用法
本文中主要介绍了linu系统下一些基础命令的用法,重点介绍了ls和date的用法。1.basename:作用:返回一个字符串参数的基本文件名称。用法:basename PATH例如:basename /usr/share/doc 返回结果为doc2.dirname:作用:返回一…
Caffe中对MNIST执行train操作执行流程解析
之前在 http://blog.csdn.net/fengbingchun/article/details/49849225 中简单介绍过使用Caffe train MNIST的文章,当时只是仿照caffe中的example实现了下,下面说一下执行流程,并精简代码到仅有10余行:1. 先注册所有层&…

华为云垃圾分类AI大赛三强出炉,ModelArts2.0让行业按下AI开发“加速键”
9月20日,华为云人工智能大赛垃圾分类挑战杯决赛在上海世博中心2019华为全联接大会会场顺利举办。经过近两个月赛程的层层筛选,入围决赛阵列的11支战队的高光时刻也如期而至。最终华为云垃圾分类挑战杯三强出炉。本次华为云人工智能大赛垃圾分类挑战杯聚焦…

王坚十年前的坚持,才有了今天世界顶级大数据计算平台MaxCompute...
如果说十年前,王坚创立阿里云让云计算在国内得到了普及,那么王坚带领团队自主研发的大数据计算平台MaxCompute则推动大数据技术向前跨越了一大步。数据是企业的核心资产,但十年前阿里巴巴的算力已经无法满足当时急剧增长数据量的需求。基于Ha…

tomcat简单配置
-----------------------------------------一、前言二、环境三、安装JDK四、安装tomcat五、安装mysql六、安装javacenter七、tomcat后台管理-----------------------------------------一、前言Tomcat是Apache 软件基金会(Apache Software Foundation)的…
使用Caffe进行手写数字识别执行流程解析
之前在 http://blog.csdn.net/fengbingchun/article/details/50987185 中仿照Caffe中的examples实现对手写数字进行识别,这里详细介绍下其执行流程并精简了实现代码,使用Caffe对MNIST数据集进行train的文章可以参考 http://blog.csdn.net/fengbingchun/…

前端也能玩转机器学习?Google Brain 工程师来支招
演讲嘉宾 | 俞玶编辑 | 伍杏玲来源 | CSDN(ID:CSDNnews)导语:9 月 7 日,在CSDN主办的「AI ProCon 2019」上,Google Brain 工程师,TensorFlow.js 项目负责人俞玶发表《TensorFlow.js 遇到小程序》的主题演讲,…

mongoDB设置用户名密码的一个要点
2019独角兽企业重金招聘Python工程师标准>>> 增加用户之前, 先选好库 use <库名> #选择admin库后可查看system.users里面的用户数据 db.system.users.find() db.createUser 这个函数填写用户名密码与权限就行了, 在这里设置库的名称没用. 一定要用用use选择好…

基于HTML5的电信网管3D机房监控应用
先上段视频,不是在玩游戏哦,是规规矩矩的电信网管企业应用,嗯,全键盘的漫游3D机房:随着PC端支持HTML5浏览器的普及,加上主流移动终端Android和iOS都已支持HTML5技术,新一代的电信网管应用几乎一致性的首选H…