【C++标准库】字符串
string filename = "test.cpp"; string::size_type idx = filename.find('.'); //size_type是string class定义的一个无正负号整数类型,size_type类型取决于string class的内存模型 //idx不能定义为int或者unsigned类型,否则与string::npos的比较动作无法有效运行 if (idx == string::npos) { cout << "find fail..." << endl; }
从标准输入设备输入一个个单词,然后字符逆序打印。
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference, 2nd Edition" * by Nicolai M. Josuttis, Addison-Wesley, 2012 * * (C) Copyright Nicolai M. Josuttis 2012. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <string> using namespace std; int main(int argc, char** argv) { const string delims(" \t,.;"); string line; // for every line read successfully while (getline(cin, line)) { string::size_type begIdx, endIdx; // search beginning of the first word begIdx = line.find_first_not_of(delims); // while beginning of a word found while (begIdx != string::npos) { // search end of the actual word endIdx = line.find_first_of(delims, begIdx); if (endIdx == string::npos) { // end of word is end of line endIdx = line.length(); } // print characters in reverse order for (int i = endIdx - 1; i >= static_cast<int>(begIdx); --i) { cout << line[i]; } cout << ' '; // search beginning of the next word begIdx = line.find_first_not_of(delims, endIdx); } cout << endl; } }
在<string>中,basic_string<>类被定义为所有string类型的基础模板类,它将字符类型、字符类型的trait、内存模型都参数化了。
C++标准库提供了若干basic_string<>的特化版本:
typedef basic_string<char> string; typedef basic_string<wchar_t> wstring; typedef basic_string<char16_t> u16string; typedef basic_string<char32_t> u32string;
C++ standard中将字符串字面常量的类型由char*改为const char*.有三个函数可以将string内容转换为字符数组或者C-String
- data()和c_str()以字符数组的形式返回string内容,在数组最后有一个结束符,所以其结果是一个内含\0字符的有效C-String
- copy()将string内容复制到字符数组中,末尾添加'\0'字符