Common operations of C++ string c

Links to the original text: https://blog.csdn.net/qq_37941471/article/details/82107077

Reproduced in: https://blog.csdn.net/qq_37941471/article/details/82107077

1. The form of the constructor of string:

string str: Generate empty strings

string s(str): Generate a string as str Copies

string s(str, strbegin,strlen): String str Subordinate Subscript strbegin Start, length is strlen The part as the initial value of the string

string s(cstr, char_len): with C_string type cstr Before char_len Six strings as strings s Initial value

string s(num ,c): generatenumindividual c Strings of characters

string s(str, stridx): String str Subordinate Subscript stridx Starting to the end of the string as the initial value of the string

eg:


    string str1;               //Generate empty strings
    string str2("123456789");  //Generate a copy of "1234456789"
    string str3("12345", 0, 3);//The result is "123"
    string str4("012345", 5);  //The result is "01234"
    string str5(5, '1');       //The result is "11111"
    string str6(str2, 2);      //The result was "3456789"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
#include <iostream>
#include <string>
using namespace std;

void test1()
{
    string str1;               //Generate empty strings
    string str2("123456789");  //Generate a copy of "1234456789"
    string str3("12345", 0, 3);//The result is "123"
    string str4("0123456", 5);  //The result is "01234"
    string str5(5, '1');       //The result is "11111"
    string str6(str2, 2);      //The result was "3456789"

    cout<<"str2:"<<str2<<endl;
    cout<<"str3:"<<str3<<endl;
    cout<<"str4:"<<str4<<endl;
    cout<<"str5:"<<str5<<endl;
    cout<<"str6:"<<str6<<endl;
}

int main()
{
    test1();
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

2. The size and capacity of string s:

1. size() and length(): Returns the number of characters of string objects that perform the same.

2. max_size(): Returns the maximum number of characters that a string object contains, and throws a length_error exception if it exceeds

3. capacity(): The maximum number of characters a string object can contain before memory is reallocated

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
void test2()
{
    string s("1234567");
    cout << "size=" << s.size() << endl;
    cout << "length=" << s.length() << endl;
    cout << "max_size=" << s.max_size() << endl;
    cout << "capacity=" << s.capacity() << endl;

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3. String string comparison:

1. C++ strings support common comparison operators (>,>=,<,<=,==,!=), and even support strings compared with C-string s (such as str<"hello").  
When using >, >=, <, <=, these operators are compared one by one in dictionary order according to the "current character characteristics". The characters in front of the dictionary are small.  
The order of comparison is from front to back. When encountering unequal characters, the size of the two strings is determined according to the comparison results of the two characters in this position (before subtracting after)
At the same time, string ("aaaa") < string (aaaaaaa).    

2. Another powerful comparison function is the member function compare(). It supports multi-parameter processing, and supports comparisons between indexed values and length-positioned substrings. 
  He returns an integer to represent the comparison result. The return value is as follows: 0: equal 1: greater than - 1: less than (A's ASCII code is 65, a's ASCII code is 97).
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
void test3()
{
    // (A's ASCII code is 65, a's ASCII code is 97)
    // After subtracting the ASCII code from the front, > 0 returns 1, < 0 returns - 1, and the same returns 0.
    string A("aBcd");
    string B("Abcd");
    string C("123456");
    string D("123dfg");

    // Comparisons between "aBcd" and "Abcd" ----- a > A
    cout << "A.compare(B): " << A.compare(B)<< endl;                          // Results: 1.

    // COMPARISON BETWEEN "cd" AND "Abcd" ----- C > A
    cout << "A.compare(2, 3, B):" <<A.compare(2, 3, B)<< endl;                // Results: 1.

    // Comparison of "cd" and "cd" 
    cout << "A.compare(2, 3, B, 2, 3):" << A.compare(2, 3, B, 2, 3) << endl;  // Results:0.


    // From the results, we can see that 0 is the subscript and 3 is the length.
    // Comparison of "123" and "123" 
    cout << "C.compare(0, 3, D, 0, 3)" <<C.compare(0, 3, D, 0, 3) << endl;    // Results:0.

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

IV. string insertion: push_back() and insert()

void  test4()
{
    string s1;

    // End a character
    s1.push_back('a');
    s1.push_back('b');
    s1.push_back('c');
    cout<<"s1:"<<s1<<endl; // s1:abc

    // insert(pos,char): insert the character char before POS in the designated position
    s1.insert(s1.begin(),'1');
    cout<<"s1:"<<s1<<endl; // s1:1abc
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

5. String concatenation string: append () & + operator

void test5()
{
    // Method 1: append()
    string s1("abc");
    s1.append("def");
    cout<<"s1:"<<s1<<endl; // s1:abcdef

    // Method 2: +Operator
    string s2 = "abc";
    /*s2 += "def";*/
    string s3 = "def";
    s2 += s3.c_str();
    cout<<"s2:"<<s2<<endl; // s2:abcdef
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

6. Traversal of string: with the help of iterator or subscription method

void test6()
{
    string s1("abcdef"); // Call a constructor once

    // Method 1: Subscription

    for( int i = 0; i < s1.size() ; i++ )
    {
        cout<<s1[i];
    }
    cout<<endl;

    // Method 2: Forward iterator

    string::iterator iter = s1.begin();
    for( ; iter < s1.end() ; iter++)
    {
        cout<<*iter;
    }
    cout<<endl;

    // Method 3: Reverse iterator
    string::reverse_iterator riter = s1.rbegin();
    for( ; riter < s1.rend() ; riter++)
    {
        cout<<*riter;
    }
    cout<<endl;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

Deletion of string: erase()

1. iterator erase(iterator p); //Delete the character referred to by P in the string

2. iterator erase(iterator first, iterator last); //Delete iterators in strings

All characters on interval [first,last)

3. String & erase (size_t POS = 0, size_t len = npos); //Delete the string from the index

The len character at the beginning of pos

4. void clear(); //Delete all characters in the string
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
void test6()
{
    string s1 = "123456789";


    // s1.erase(s1.begin()+1);//Result: 13456789
    // s1.erase(s1.begin()+1,s1.end()-2);//Result: 189
    s1.erase(1,6);                       // Results: 189
    string::iterator iter = s1.begin();
    while( iter != s1.end() )
    {
        cout<<*iter;
        *iter++;
    }
    cout<<endl;

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

8. Character substitution of string:

1. string & replace (size_t pos, size_t n, const char*s); //

n characters starting with pos index, replaced by string s

2. string & replace (size_t pos, size_t n, size_t n1, char c); // replace the n characters of the current string starting from the POS index with N1 character c

3. String & replace (iterator i1, iterator i2, const char* s); // Replace strings in the current string [i1,i2) interval with strings S
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
void test7()
{
    string s1("hello,world!");

    cout<<s1.size()<<endl;                     // Results:12.
    s1.replace(s1.size()-1,1,1,'.');           // Result: hello,world.

    // Here 6 denotes subscript 5 denotes length
    s1.replace(6,5,"girl");                    // Result: hello,girl.
    // s1.begin(),s1.begin()+5 are left closed right open intervals
    s1.replace(s1.begin(),s1.begin()+5,"boy"); // Results: boy,girl.
    cout<<s1<<endl;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

9. Case-to-case conversion of string: tolower() and toupper() functions or transform ation algorithm in STL

Method 1: Use the method before C language, use function to transform.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s = "ABCDEFG";

    for( int i = 0; i < s.size(); i++ )
    {
        s[i] = tolower(s[i]);
    }

    cout<<s<<endl;
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

Method 2: toupper and tolower are combined with STL transform algorithm to realize this function.

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    string s = "ABCDEFG";
    string result;

    transform(s.begin(),s.end(),s.begin(),::tolower);
    cout<<s<<endl;
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Another blog about me:
C++ Converts string to case
https://blog.csdn.net/qq_37941471/article/details/81988702

10. string search: find

1. size_t find (constchar* s, size_t pos = 0) const;

  //Starting at the pos index position of the current string, find the substring s and return the location index found.

    -1Indicates that no substring can be found

2. size_t find (charc, size_t pos = 0) const;

  //Starting at the pos index position of the current string, look up character c and return the location index found.

    -1Indicates that a character cannot be found

3. size_t rfind (constchar* s, size_t pos = npos) const;

  //Starting at the pos index position of the current string, look up the substring s backwards and return the location index found.

    -1Indicates that no substring can be found

4. size_t rfind (charc, size_t pos = npos) const;

  //At the beginning of the pos index position of the current string, look up the character c backwards, return the location index found, -1 means that the character cannot be found.

5. size_tfind_first_of (const char* s, size_t pos = 0) const;

  //At the beginning of the pos index position of the current string, find the character of the substring s, return the location index found, -1 means that the character cannot be found.

6. size_tfind_first_not_of (const char* s, size_t pos = 0) const;

  //At the beginning of the pos index position of the current string, find the first character not located in the substring s, return the location index found, -1 indicates that the character cannot be found.

7. size_t find_last_of(const char* s, size_t pos = npos) const;

  //At the beginning of the pos index position of the current string, find the last character in the substring s, return the location index found, -1 indicates that the character cannot be found.

8. size_tfind_last_not_of (const char* s, size_t pos = npos) const;

 //At the beginning of the pos index position of the current string, find the last character not located in the substring s, return the location index found, -1 indicates that the substring cannot be found.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
void test8()
{
    string s("dog bird chicken bird cat");

    //String lookup - - - returns the subscript of the initial letter in the string after finding it

    // 1. Find a string
    cout << s.find("chicken") << endl;        // The results are as follows:9

    // 2. Look for the character'i'from the subscript of 6, and return the subscript of the first I found.
    cout << s.find('i',6) << endl;            // The result is: 11

    // 3. Find the string from the end of the string, and return the subscript of the initial letter in the string.
    cout << s.rfind("chicken") << endl;       // The results are as follows:9

    // 4. Search for characters from the end of the string
    cout << s.rfind('i') << endl;             // The result is: 18 - - - because it starts at the end, it returns the first character it finds.

    // 5. Find the first character belonging to string s in this string
    cout << s.find_first_of("13br98") << endl;  // The result is: 4 - B

    // 6. Find the first character in the string that does not belong to the string s - --- match dog first, then bird does not match, so print 4
    cout << s.find_first_not_of("hello dog 2006") << endl; // The results are as follows:4
    cout << s.find_first_not_of("dog bird 2006") << endl;  // The results are as follows:9

    // 7. Find the first character belonging to string s at the end of the string
    cout << s.find_last_of("13r98") << endl;               // The result is: 19

    // 8. Find the first character that does not belong to the string s a t the end of the string - - - first match T - - A - - c, then the space matches not, so print 21
    cout << s.find_last_not_of("teac") << endl;            // The result is: 21

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

11. string sorting: sort(s.begin(),s.end())

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

void test9()
{
    string s = "cdefba";
    sort(s.begin(),s.end());
    cout<<"s:"<<s<<endl;     // Results: abcdef
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

string's Segmentation/Interception string: strtok () & substr ()

strtok(): split string

void test10()
{
    char str[] = "I,am,a,student; hello world!";

    const char *split = ",; !";
    char *p2 = strtok(str,split);
    while( p2 != NULL )
    {
        cout<<p2<<endl;
        p2 = strtok(NULL,split);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

void test11()
{
    string s1("0123456789");
    string s2 = s1.substr(2,5); // Result: 23456 - - - Parametric 5 indicates the length of the intercepted string
    cout<<s2<<endl;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Tags: ascii less C

Posted on Wed, 31 Jul 2019 20:54:41 -0700 by hyabusa