C++ string

  1,写时复制。例子:

int main() 
{
string str1 = "hello world"; string str2 = str1; printf("Sharing the memory:\n"); printf("\tstr1's address:%x\n", str1.c_str()); // str1's address:501028 printf("\tstr2's address:%x\n", str2.c_str()); // str2's address:501028 str1[1] = 'w'; printf("After Copy_On_Write:\n"); printf("\tstr1's address:%x\n", str1.c_str()); // str1's address:501058 printf("\tstr2's address:%x\n", str2.c_str()); // str2's address:501028 return 0; }

  2,find系列的成员函数(可参照源代码/usr/include/c++/4.1.2/bits/basic_string.tcc)。

  首先需要了解,这个系列的函数都返回string::size_type(无符号)类型;特殊值string::npos是size_type类型的最大值(比如在tlinux-sles10 64Bit中它的值是18446744073709551615)。

  它们的功能都类似:若能找到目标则返回其出现的位置,否则返回string::npos(因此不要直接拿这些函数的返回值去和0比较)。比如:

  s.find(ch|subs, pos); 对于s从下标为pos的位置开始查找字符ch或子串subs。

  s.find_first_of(ch|subs, pos); 从pos处向后遍历s,找到第一个能与ch匹配或被subs包含的字符。

  s.find_last_of(ch|subs, pos); 从pos处向前遍历s,找到第一个能与ch匹配或被subs包含的字符。

int main()
{
    string s = "hello world";

    cout << s.find_first_of("telh", 0) << endl;    // 结果为0
    cout << s.find_last_of("telo", s.length() - 1) << endl;    // 结果为9
}

 

不断学习中。。。

你可能感兴趣的:(String)