• C++之std::string


    string类与头文件包含:#include

    string构造方法:

    1. // string constructor
    2. #include
    3. #include
    4. int main ()
    5. {
    6. std::string s0 ("Initial string"); //根据已有字符串构造新的string实例
    7. // constructors used in the same order as described above:
    8. std::string s1; //构造一个默认为空的string
    9. std::string s2 (s0); //通过复制一个string构造一个新的string
    10. std::string s3 (s0, 8, 3); //通过复制一个string的一部分来构造一个新的string。8为起始位置,3为偏移量。
    11. std::string s4 ("A character sequence"); //与s0构造方式相同。
    12. std::string s5 ("Another character sequence", 12); //已知字符串,通过截取指定长度来创建一个string
    13. std::string s6a (10, 'x'); //指定string长度,与一个元素,则默认重复该元素创建string
    14. std::string s6b (10, 42); // 42 is the ASCII code for '*' //通过ASCII码来代替s6a中的指定元素。
    15. std::string s7 (s0.begin(), s0.begin()+7); //通过迭代器来指定复制s0的一部分,来创建s7
    16. std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
    17. std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6a: " << s6a;
    18. std::cout << "\ns6b: " << s6b << "\ns7: " << s7 << '\n';
    19. return 0;
    20. }
    21. 输出:
    22. s1:
    23. s2: Initial string
    24. s3: str
    25. s4: A character sequence
    26. s5: Another char
    27. s6a: xxxxxxxxxx
    28. s6b: **********
    29. s7: Initial

    string::operation =  :使用 = 运算符也可以创建string。

    1. // string assigning
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str1, str2, str3;
    7. str1 = "Test string: "; // c-string //通过=运算符来给已创建的string“赋值”
    8. str2 = 'x'; // single character
    9. str3 = str1 + str2; // string
    10. //注意这里重载了"+",string类的"+"可以理解为胶水,将两个string类型连接起来了
    11. std::cout << str3 << '\n';
    12. return 0;
    13. }
    14. 输出:
    15. Test string: x

     string-Iterators:string也有迭代器,熟练掌握迭代器的使用,有时能避免繁杂的for循环,但代码更有灵活性。

    1. // string::begin/end
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str ("Test string");
    7. for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
    8. std::cout << *it;
    9. std::cout << '\n';
    10. return 0;
    11. }
    12. 输出:
    13. Test string

     string-capacity:

    1. // string::size
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str ("Test string");
    7. std::cout << "The size of str is " << str.size() << " bytes.\n";
    8. return 0;
    9. }
    10. //Output:
    11. //The size of str is 11 bytes
    12. // string::length
    13. #include <iostream>
    14. #include <string>
    15. int main ()
    16. {
    17. std::string str ("Test string");
    18. std::cout << "The size of str is " << str.length() << " bytes.\n";
    19. return 0;
    20. }
    21. //Output:
    22. //The size of str is 11 bytes

     比较一下size与length,其实二者没有任何区别,length是因为沿用C语言的习惯而保留下来的,string类最初只有length,引入STL之后,为了兼容又加入了size,它是作为STL容器的属性存在的,便于符合STL的接口规则,以便用于STL的算法。

    string::clear:擦除字符串的内容,成为一个空字符串(长度为0个字符)。

    调用方式:

    str.clear();

    string::empty:判断string其中内容是否为空。再判断一个string是否为空时,可以使用该函数,也可以使用size()函数与length()函数来获取string的长度,然后判断长度是否为0。但优先使用empty()函数,因为该函数运行速度更快。

    string-element access

    .string::operator[]:获取字符串的字符,返回字符串中位置pos处字符的引用。示例代码如下 

    1. // string::operator[]
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str ("Test string");
    7. for (int i=0; i<str.length(); ++i)
    8. {
    9. std::cout << str[i];
    10. }
    11. return 0;
    12. }
    13. 输出:
    14. Test string

    .string::at:获取字符串中的字符,返回字符串中位置pos处字符的引用。该函数自动检查pos是否是字符串中字符的有效位置(即pos是否小于字符串长度),如果不是,则会抛出out_of_range异常。示例代码如下

    1. // string::at
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str ("Test string");
    7. for (unsigned i=0; i<str.length(); ++i)
    8. {
    9. std::cout << str.at(i);
    10. }
    11. return 0;
    12. }
    13. //Output
    14. //Test string

    operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range异常,下标运算符[]不提供检查访问。[]访问的速度比at()要快,但不作越界检查.用[]访问之前, 要对下标进行检查( > string::npos && < string::size())

    string::back:访问最后一个字符,返回对字符串最后一个字符的引用。这个函数不能在空字符串上调用。

    1. // string::back
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str ("hello world.");
    7. str.back() = '!';
    8. std::cout << str << '\n';
    9. return 0;
    10. }
    11. //Output:
    12. //hello world! //将原来的最后一个'.' 变为了'!'

    string::front:访问第一个字符,返回对字符串的第一个字符的引用。与成员string :: begin不同,它将一个迭代器返回给这个相同的字符,这个函数返回一个直接引用。这个函数不能在空字符串上调用。

    1. // string::front
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str ("test string");
    7. str.front() = 'T';
    8. std::cout << str << '\n';
    9. return 0;
    10. }
    11. //Output:
    12. //Test string //将原来的第一个't'变为了'T'

     string-modifiers:

    string::operator+=:附加到字符串。通过在当前值的末尾添加其他字符来扩展字符串: 

    1. // string::operator+=
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string name ("John");
    7. std::string family ("Smith");
    8. name += " K. "; // c-string
    9. name += family; // string
    10. name += '\n'; // character
    11. std::cout << name;
    12. return 0;
    13. }
    14. //Output:
    15. //John K. Smith

    string::append:附加到字符串。通过在当前值的末尾添加其他字符来扩展字符串:

    1. // appending to string
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str;
    7. std::string str2="Writing ";
    8. std::string str3="print 10 and then 5 more";
    9. // used in the same order as described above:
    10. str.append(str2); // "Writing "
    11. str.append(str3,6,3); // "10 "
    12. str.append("dots are cool",5); // "dots "
    13. str.append("here: "); // "here: "
    14. str.append(10u,'.'); // ".........."
    15. str.append(str3.begin()+8,str3.end()); // " and then 5 more"
    16. str.append<int>(5,0x2E); // "....."
    17. std::cout << str << '\n';
    18. return 0;
    19. }
    20. //Output:
    21. //Writing 10 dots here: .......... and then 5 more.....

    string::push_ back:追加字符到字符串。将字符c附加到字符串的末尾,将其长度增加1。与vector、set、map等容器的push_ back类似功能。

    string::assign:将内容分配给字符串。为字符串分配一个新值,替换其当前内容。

    string::insert:插入字符串。在由pos(或p)指示的字符之前的字符串中插入附加字符:

    1. // inserting into a string
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str="to be question";
    7. std::string str2="the ";
    8. std::string str3="or not to be";
    9. std::string::iterator it;
    10. // used in the same order as described above:
    11. //后面注释中()括号的作用只是帮助显示插入的内容与位置信息。实际string中并没有这对括号
    12. str.insert(6,str2); // to be (the )question
    13. str.insert(6,str3,3,4); // to be (not )the question
    14. str.insert(10,"that is cool",8); // to be not (that is )the question
    15. str.insert(10,"to be "); // to be not (to be )that is the question
    16. str.insert(15,1,':'); // to be not to be(:) that is the question
    17. it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
    18. str.insert (str.end(),3,'.'); // to be, not to be: that is the question(...)
    19. str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
    20. std::cout << str << '\n';
    21. return 0;
    22. //Output:
    23. //to be, or not to be: that is the question...
    24. }

    string::erase:擦除字符串中的字符。擦除部分字符串,减少其长度

    1. // string::erase
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str ("This is an example sentence.");
    7. std::cout << str << '\n';
    8. //后面注释有两部分,上一行是当前字符串内容,下一行是箭头,表示的意思就是箭头指向内容是处理的内容
    9. // "This is an example sentence."
    10. str.erase (10,8); // ^^^^^^^^
    11. std::cout << str << '\n'; //消除第11到第19之间的字符。即" example",注意,有一个空格符
    12. // "This is an sentence."
    13. str.erase (str.begin()+9); // ^
    14. std::cout << str << '\n'; //消除第10个字符,即begin()后9个字符:'n'
    15. // "This is a sentence."
    16. str.erase (str.begin()+5, str.end()-9); // ^^^^^
    17. std::cout << str << '\n'; //消除begin()后5个字符,end()前9个字符。
    18. // "This sentence."
    19. return 0;
    20. }

    string::replace:替换字符串的一部分。替换以字符pos开头的字符串部分,并通过新内容跨越len字符(或[i1,i2之间的范围内的字符串部分)):

    1. // replacing in a string
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string base="this is a test string.";
    7. std::string str2="n example";
    8. std::string str3="sample phrase";
    9. std::string str4="useful.";
    10. // replace signatures used in the same order as described above:
    11. // Using positions: 0123456789*123456789*12345
    12. std::string str=base; // "this is a test string."
    13. // ^^^^^
    14. str.replace(9,5,str2); // "this is an example string." (1)
    15. // ^^^^^^^^^ ^^^^^^
    16. str.replace(19,6,str3,7,6); // "this is an example phrase." (2)
    17. // ^^^^^^
    18. str.replace(8,10,"just a"); // "this is just a phrase." (3)
    19. str.replace(8,6,"a shorty",7); // "this is a short phrase." (4)
    20. str.replace(22,1,3,'!'); // "this is a short phrase!!!" (5)
    21. // Using iterators: 0123456789*123456789*
    22. str.replace(str.begin(),str.end()-3,str3); // "sample phrase!!!" (1)
    23. str.replace(str.begin(),str.begin()+6,"replace"); // "replace phrase!!!" (3)
    24. str.replace(str.begin()+8,str.begin()+14,"is coolness",7); // "replace is cool!!!" (4)
    25. str.replace(str.begin()+12,str.end()-4,4,'o'); // "replace is cooool!!!" (5)
    26. str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful." (6)
    27. std::cout << str << '\n';
    28. return 0;
    29. }

    string::swap:交换字符串值。通过str的内容交换容器的内容,str是另一个字符串对象。 长度可能有所不同。在对这个成员函数的调用之后,这个对象的值是str在调用之前的值,str的值是这个对象在调用之前的值。请注意,非成员函数存在具有相同名称的交换,并使用与此成员函数相似的优化来重载该算法。

    1. // swap strings
    2. #include <iostream>
    3. #include <string>
    4. main ()
    5. {
    6. std::string buyer ("money");
    7. std::string seller ("goods");
    8. std::cout << "Before the swap, buyer has " << buyer;
    9. std::cout << " and seller has " << seller << '\n';
    10. seller.swap (buyer);
    11. std::cout << " After the swap, buyer has " << buyer;
    12. std::cout << " and seller has " << seller << '\n';
    13. return 0;
    14. //Output:
    15. //Before the swap, buyer has money and seller has goods
    16. // After the swap, buyer has goods and seller has money
    17. }

    string::pop_back:删除最后一个字符。擦除字符串的最后一个字符,有效地将其长度减1:

    1. // string::pop_back
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str ("hello world!");
    7. str.pop_back();
    8. std::cout << str << '\n';
    9. return 0;
    10. //Output
    11. //hello world
    12. }

    string-string operations: 

     string::c_str:获取C字符串等效。返回一个指向包含以空字符结尾的字符序列(即C字符串)的数组的指针,该字符串表示字符串对象的当前值。该数组包含相同的字符序列,这些字符组成字符串对象的值,并在末尾添加一个附加的终止空字符(’\ 0’)。

    .string::copy:从字符串复制字符序列。将字符串对象的当前值的子字符串复制到s指向的数组中。 这个子字符串包含从位置pos开始的len字符。该函数不会在复制内容的末尾添加空字符。

    1. // string::copy
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. char buffer[20];
    7. std::string str ("Test string...");
    8. std::size_t length = str.copy(buffer,6,5);
    9. buffer[length]='\0';
    10. std::cout << "buffer contains: " << buffer << '\n';
    11. return 0;
    12. }
    13. //Output:
    14. //buffer contains: string

    string::find:在字符串中查找内容。在字符串中搜索由其参数指定的序列的第一次出现。当指定pos时,搜索仅包括位置pos处或之后的字符,忽略包括pos之前的字符在内的任何可能的事件。注意,与成员find_first_of不同,只要有一个以上的字符被搜索,仅仅这些字符中的一个匹配是不够的,但是整个序列必须匹配。返回值:第一场比赛的第一个字符的位置。如果没有找到匹配,函数返回string :: npos
     

    1. // string::find
    2. #include <iostream> // std::cout
    3. #include <string> // std::string
    4. int main ()
    5. {
    6. std::string str ("There are two needles in this haystack with needles.");
    7. std::string str2 ("needle");
    8. // different member versions of find in the same order as above:
    9. std::size_t found = str.find(str2);
    10. if (found!=std::string::npos)
    11. std::cout << "first 'needle' found at: " << found << '\n';
    12. found=str.find("needles are small",found+1,6);
    13. if (found!=std::string::npos)
    14. std::cout << "second 'needle' found at: " << found << '\n';
    15. found=str.find("haystack");
    16. if (found!=std::string::npos)
    17. std::cout << "'haystack' also found at: " << found << '\n';
    18. found=str.find('.');
    19. if (found!=std::string::npos)
    20. std::cout << "Period found at: " << found << '\n';
    21. // let's replace the first needle:
    22. str.replace(str.find(str2),str2.length(),"preposition");
    23. std::cout << str << '\n';
    24. return 0;
    25. //Output
    26. //first 'needle' found at: 14
    27. //second 'needle' found at: 44
    28. //'haystack' also found at: 30
    29. //Period found at: 51
    30. //There are two prepositions in this haystack with needles
    31. }

    string::substr:生成子字符串。返回一个新构造的字符串对象,其值初始化为此对象的子字符串的副本。子字符串是从字符位置pos开始的对象的一部分,并且跨越了len字符(或者直到字符串的末尾,以先到者为准)。

    1. // string::substr
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str="We think in generalities, but we live in details.";
    7. // (quoting Alfred N. Whitehead)
    8. std::string str2 = str.substr (3,5); // "think"
    9. std::size_t pos = str.find("live"); // position of "live" in str 返回pos类型size_t
    10. std::string str3 = str.substr (pos); // get from "live" to the end
    11. std::cout << str2 << ' ' << str3 << '\n';
    12. return 0;
    13. //Output:
    14. //think live in details.
    15. }

    string::compare:比较字符串。将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。被比较的字符串是字符串对象的值或者 - 如果使用的签名具有pos和len参数 - 在字符位置pos处开始的子字符串,并且跨越len字符。该字符串与比较字符串进行比较,该比较字符串由传递给该函数的其他参数确定。
     

    1. // comparing apples with apples
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string str1 ("green apple");
    7. std::string str2 ("red apple");
    8. if (str1.compare(str2) != 0) //!=0成立
    9. std::cout << str1 << " is not " << str2 << '\n';
    10. if (str1.compare(6,5,"apple") == 0) //==0成立
    11. std::cout << "still, " << str1 << " is an apple\n";
    12. if (str2.compare(str2.size()-5,5,"apple") == 0) //==0成立
    13. std::cout << "and " << str2 << " is also an apple\n";
    14. if (str1.compare(6,5,str2,4,5) == 0) //==0成立
    15. std::cout << "therefore, both are apples\n";
    16. return 0;
    17. }

    string::find_ first_ of:在字符串中查找字符。在字符串中搜索与其参数中指定的任何字符匹配的第一个字符。当指定pos时,搜索仅包括位置pos或之后的字符,忽略pos之前的任何可能的事件。请注意,对于序列中的一个字符来说,就足够了(不是全部)。 请参阅string :: find以查找与整个序列匹配的函数。
    string::find_ first_ not_of:查找字符串中没有字符。在字符串中搜索与其参数中指定的任何字符不匹配的第一个字符。指定pos时,搜索仅包含位置pos或之后的字符,忽略该字符之前的任何可能的事件。

    1. // string::find_first_of
    2. #include <iostream> // std::cout
    3. #include <string> // std::string
    4. #include <cstddef> // std::size_t
    5. int main ()
    6. {
    7. std::string str ("Please, replace the vowels in this sentence by asterisks.");
    8. std::size_t found = str.find_first_of("aeiou");
    9. //下面的循环实现了找到str中,”aeiou“中所有字符:'a''e''i''o''u',并将其都替换为'* '
    10. while (found!=std::string::npos)
    11. {
    12. str[found]='*';
    13. found=str.find_first_of("aeiou",found+1);
    14. }
    15. std::cout << str << '\n';
    16. return 0;
    17. //Output
    18. //Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.
    19. }

    string::find_ last_of:从结尾查找字符串。在字符串中搜索与其参数中指定的任何字符匹配的最后一个字符。当pos被指定时,搜索只包含位置pos之前或之前的字符,忽略pos之后的任何可能的事件。

    1. // string::find_last_of
    2. #include <iostream> // std::cout
    3. #include <string> // std::string
    4. #include <cstddef> // std::size_t
    5. void SplitFilename (const std::string& str)
    6. {
    7. std::cout << "Splitting: " << str << '\n';
    8. std::size_t found = str.find_last_of("/\\"); //在str中搜索与"/\\"中任一个字符匹配的最后一个字符。
    9. std::cout << " path: " << str.substr(0,found) << '\n'; //pos就是匹配到的位置。0~pos
    10. std::cout << " file: " << str.substr(found+1) << '\n'; //pos~string结束
    11. }
    12. int main ()
    13. {
    14. std::string str1 ("/usr/bin/man");
    15. std::string str2 ("c:\\windows\\winhelp.exe");
    16. SplitFilename (str1);
    17. SplitFilename (str2);
    18. return 0;
    19. \\Output
    20. \\Splitting: /usr/bin/man
    21. \\ path: /usr/bin
    22. \\ file: man
    23. \\Splitting: c:\windows\winhelp.exe
    24. \\ path: c:\windows
    25. \\ file: winhelp.exe
    26. }

    string::npos
    size_ t的最大值。npos是一个静态成员常量值,对于size_ t类型的元素具有最大的可能值。这个值在字符串的成员函数中用作len(或sublen)参数的值时,意思是“直到字符串结尾”。作为返回值,通常用来表示不匹配。这个常量被定义为-1,这是因为size_ t是一个无符号整型,它是这种类型最大的可表示值

    operator>> (string)与operator<< (string):示例代码如下:

    1. // extract to string
    2. #include <iostream>
    3. #include <string>
    4. main ()
    5. {
    6. std::string name;
    7. std::cout << "Please, enter your name: ";
    8. std::cin >> name;
    9. std::cout << "Hello, " << name << "!\n";
    10. return 0;
    11. }

     .getline (string):示例代码如下:

    1. // extract to string
    2. #include <iostream>
    3. #include <string>
    4. int main ()
    5. {
    6. std::string name;
    7. std::cout << "Please, enter your full name: ";
    8. std::getline (std::cin,name);
    9. std::cout << "Hello, " << name << "!\n";
    10. return 0;
    11. }

    在以往的C++中,比较难转换的,要使用std::stringstream,这个使用起来怎么感觉都有点麻烦,还是喜欢使用itoa()的实现,现在C++11带来新的std::to_string(),就更加方便了,如下:

    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);
     

    1. // to_string example
    2. #include <iostream> // std::cout
    3. #include <string> // std::string, std::to_string
    4. int main ()
    5. {
    6. std::string pi = "pi is " + std::to_string(3.1415926);
    7. std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
    8. std::cout << pi << '\n';
    9. std::cout << perfect << '\n';
    10. return 0;
    11. }

  • 相关阅读:
    Centos/Ubuntu安装redis
    【Linux】网络编程基础
    Redis(五)
    DDD—Repository仓储&工厂模式
    道可云元宇宙每日资讯|2023焦作市文旅元宇宙产业发展座谈会举行
    网络安全(黑客技术)—2024自学手册
    机器学习是什么?
    大数据必学Java基础(九十七):事务及回滚点
    搭建vue3项目并git管理
    Pytorch框架详解
  • 原文地址:https://blog.csdn.net/yefei123123/article/details/126226390