Reference:The C++ Programming Language 4th edition (Bjarne Stroustrup)
1.字符分类(Character Classification)
#include <cctype>
isspace(c) //' ', '\t', '\n', '\v', '\f', '\r'
isalpha(c) //'a'..'z', 'A..Z'
isdigit(c) //'0'..'9'
isxdigit(c) //'0'..'9',''a'..'f', 'A'..'F'
isupper(c) //uppercase
islower(c) //lowercase
isalnum(c) //isalpha(c) or isdigit(c)
iscntrl(c) //ASCII 0..31 and 127
ispunct(c) //not a letter, digit, whitespace, or invisible control charater
isprint(c) //printable(ASCII ‘ ‘..’~‘)
isgraph(c) //isalpha(c) or isdigit(c) or ispunct(c)
大小写转换函数
toupper(c) //to uppercase
tolower(c) //to lowercase
2. 字符串
#include <string>
标准库提供通用的字符串模板basic_string:
1. basic_string保证字符存储在连续的内存中
2. basic_string强力保证如果有异常抛出,字符串保持不变
专门化的字符串类型:
using string = basic_string<char>
using u16string = basic_string<char16_t>
using u32string = basic_string<char32_t>
using wstring = basic_string<wchar_t>
3. string vs. C-style strings
(1)连接
//C++ style
string address(cosnt string& identifier, const string& domain)
{
return identifier + '@' + domain;
}
//C style
char* address(cosnt char* identifier, const char* domain)
{
int iden_len = strlen(identifier);
int dom_len = strlen(domain);
char *addr = (char*) malloc(iden_len+dom_len+2);
strcpy(addr, identifier);
addr[iden_len] = '@';
strcpy(addr+iden_len+1, domain);
return addr;
}
(2)赋值与比较
//C++ style
void test()
{
string s1 = "Ring";
if (s1 != "Ring") insanity();
if (s1< "Opera") cout << "check";
string s2 = address(s1, "Valkyrie");
}
//C style
void test()
{
char s1[] = "Ring";
if (strcmp(s1,"Ring") != 0) insanity();
if (strcmp(s1, "Opera") < 0) cout << "check";
char* s2 = address(s1, "Valkyrie");
free(s2);
}
(3)排序
//C++ style
void sortstr()
{
vector<string> vs = {"Grieg", "Williams", "Bach", "Handel"};
sort(vs.begin(), vs.end());
}
//C style
void sortstr()
{
const char* as[] = {"Grieg", "Williams", "Bach", "Handel"};
qsort(as, sizeof(*as), sizeof(as)/sizeof(*as), (int(*)(const void*, const void*))strcmp);
}
4. 构造函数(Constructor)
(1) default
explicit basic_string (const allocator_type& alloc = allocator_type());
std::string s1;
s1:
(2) copy
basic_string (const basic_string& str);basic_string (const basic_string& str,
const allocator_type& alloc = allocator_type());
std::string s0 ("Initial string");
std::string s2(s0);
s2: Initial string
(3) substring: 复制str中从pos开始(注意下标从0开始),长度为len的字符串(并不是[begin, end))
basic_string (const basic_string& str, size_type pos, size_type len = npos,
const allocator_type& alloc = allocator_type());