Summary of common function usage of string in c++ _C language _ Home of scripts

Summary of common function usage of string in c++

Updated: May 08, 2023 12:14:23 Submitted by: jingxian
The following is a detailed analysis of the usage of common functions in c++ string, and the friends who need it can come over for reference

Introduction to standard c++ string class functions

Note that the reason why CString abandonsthe char* string in favor of the C++ standard library string class is that compared with the former, it does not have to worry about the adequacy of memory, string length, etc., and it appears as a class. He integrates enough operational functions to do what we need in most cases (even 100%). We can use = for assignment, == for comparison, and + for concatenation (isn't that easy?). . We can think of it as a basic C++ data type.

All right, let's get down to business... First, in order to use the string type in our program, we must include the header file .

As follows: #include // Note that this is not string.h string.h is the C string header file #include using namespace std;

1. Declare a C++ string

Declaring a string variable is simple:

string Str;

So we're declaring a string variable, but since we're a class, we have constructors and destructors. The above declaration takes no arguments, so we simply use string's default constructor, which initializes Str to an empty string. The constructor and destructor of the String class are as follows:

a) string s; // Generates an empty string s b) string s(str) // The copy constructor generates a replica of str c) string s(str,stridx) // treats the part of string str that "begins at position stridx" as the initial value of the string d) string s(str,stridx,strlen) // Take the part of the string str that "begins with stridx and is at most strlen" as the initial value of the string e) string s(cstr) // Take the C string as the initial value of s f) string s(chars,chars_len) // takes the chars_len character before the C string as the initial value of the string s. g) string s(num,c) // Generate a string containing num c characters h) string s(beg,end) // Use the interval beg; The characters in end(excluding end) are used as the initial value of the string s.) s.~string() // All characters are destroyed to free memory

It's all very simple. I won't explain it.

2. String manipulation function

Here is the focus of C++ string, I first listed the various operation functions, do not like to read all the functions can find their favorite function here, and then to see his detailed explanation.

a) =,assign() // Assign a new value b) swap() // Swap the contents of the two strings c) +=,append(),push_back() // Add characters at the end d) insert() // Insert characters e) erase() // Delete characters f) Clear () / / delete all characters g) replace ()/h) + / / / replace characters series connection string I) = =,! =, <, < =, >, > =, compare compare strings () / / j) size (), length () / / return character number k) max_size () / / return the possible maximum number of characters l) empty / / to determine whether a string is empty () m) capacity() // Returns the character capacity before reallocation n) reserve() // Reserve a certain amount of memory to hold a certain number of characters o) [], at() // Access a single character p) >>,getline() // Reads a value from the stream q) << // Writes a value to the stream r) copy() // Assigns a value to a C_string s) c_str() // Returns the content as C_string t) data() // Returns the content as an array of characters u) substr() // Returns a substring v) Search function w)begin() end() // Provides support for iterators like STL x) rbegin() rend() // reverse iterator y) get_allocator() // Returns the configurator

The following details:

2.1 C++ string and C string conversion

The methods provided by C++ to get the corresponding C_string from a C++ string are using data(), c_str(), and copy(), where data() returns the contents of the string as an array of characters without adding '/0'. c_str() returns an array of characters ending in '/0', while copy() copies or writes the contents of the string to the existing c_string or character array. C++ strings do not end in '/0'. My advice is to use C++ strings whenever possible in your program, unless you absolutely have to. Since this is just a brief introduction, the detailed introduction is skimmed, anyone who wants to know more about the precautions in use can leave me a message (to my inbox). I'll explain in detail.

2.2 Size and capacity functions

a C++ string has three sizes: a) the number of existing characters, and the functions size() and length() are equivalent. Empty() checks if the string is empty. b)max_size() This size refers to the maximum number of characters that can be contained in the current C++ string, most likely due to the limitations of the machine itself or the size of the contiguous memory where the string is located. We don't normally have to care about him. He should be big enough for us. However, if there is not enough, the length_error exception will be raised. c)capacity() The maximum number of characters that a string can contain before reallocating memory. Another thing to point out here is the reserve() function, which reallocates memory for string. The size of the reallocation is determined by its argument, which defaults to 0, in which case the string is involuntarily shrunk. It is also necessary to repeat the C++ string and C string conversion question, many people will encounter such a problem, their own program to call someone else's function, class what (such as the database connection function Connect(char*,char*)), but other people's function parameters are in the form of char*, and we know that, The array of characters returned by c_str() and data() is owned by the string, so it is a const char*. In order to be used as an argument to the above mentioned functions, it must also be copied to a char*, and our principle is not to use C strings if we can not use them. So, here's how we deal with it: If the function does not change the contents of the argument (i.e. char*), we can use Connect((char*)UserID.c_str(), (char*)PassWD.c_str()), but this is dangerous. Since the converted string can actually be modified (try it yourself if you are interested), I emphasize that unless the argument is not modified during the function call, it must be copied to a char*. Of course, it is safer to copy it to a char* in any case. We also pray for the people who are still programming with C strings today (it's fair to say that they are masters, maybe they started programming when we were still wearing pants, lol...). The functions we write are fairly canonical, so we don't have to cast them.

2.3 Element Access

We can use the subscript operator [] and the function at() to access the characters contained in the element. However, it should be noted that the [] operator does not check whether the index is valid (valid index 0~str.length()), and if the index is invalid, it will cause undefined behavior. at() checks and throws an out_of_range exception if the index is invalid when using at().

One exception I have to say is const string a; The [] operator is still valid if the index value is a.length(), and its return value is' /0 '. In all other cases, the a.length() index is invalid.

Examples are as follows:

const string Cstr(“const string”); string Str(“string”); Str[3]; //ok Str.at(3); //ok Str[100]; // Undefined behavior Str.at(100); //throw out_of_range Str[str.length()] // undefined behavior Cstr[cstr.length ()] // Returns' /0' str.at (str.length()); //throw out_of_range Str[str.length()); //throw out_of_range Cstr.at(Cstr.length()) ////throw out_of_range

I do not approve of reference or pointer assignments like the following:

char& r=s[2];
char* p= &s[3];

Because as soon as a reallocation occurs, r and p immediately fail. The way to avoid it is not to use it.

2.4 Comparison function

C ++ strings support common comparison operators (>,>=,<,<=,==,!). =), and even supports comparisons between string and C-string (e.g. str< "hello"). When using the operators >,>=,<,<=, characters are compared one by one in lexicographic order according to the "current character characteristic". The first character of the dictionary sort is small, and the comparison order is from front to back. If the characters are not equal, the size of the two strings is determined according to the comparison result of the two characters in this position. Meanwhile, string(" aaaa ") <string(aaaaa).

Another powerful comparison function is the member function compare(). It supports multi-parameter processing and supports comparison with index values and length positioning substrings. He returns an integer to represent the result of the comparison, with the following meanings: 0- equal > 0- greater than <0- less than. Examples are as follows:

string s(“abcd”); s.compare(“abcd”); // Return to 0 s.compare(" dcba "); // Returns a value less than 0 s.compare(" ab "); // Return a value greater than 0 s.compare(s); // equitiess.com pare(0,2,s,2,2); // Compare with "ab" and "cd" less than zeross.com pare(1,2, "bcx",2); // Compare with "bc" and "bc".

How's that?? Functional enough! What? Still not enough to satisfy your appetite? Okay, well, wait. There's a more personalized comparison algorithm. As a hint, the STL comparison algorithm is used. What? Don't know anything about STL? Damn it, you fix it!

2.5 Changing Content

This is a large part of string manipulation. The first assignment, of course, is to use the operator =, and the new value can be a string(e.g., s=ns), c_string(e.g., s= "gaint") or even a single character (e.g., s= 'j'). You can also use the member function assign(), which gives you more flexibility in assigning values to strings. Here are some examples:

s.assign(str); // Do not say s.assign(str,1,3); // If str is "iamangel", it assigns "ama" to the string s.assign(str,2,string::npos); // Assign the string str to s.assign(" gaint ") from the index value 2 to the end; // Don't say s.assign(" nico ",5); // Assign 'n' 'I' 'c' 'o' '/0' to the string s.assign(5, 'x'); // Assign five x's to the string

There are three ways to clear the string: s= "; s.clear(); s.erase(); (I increasingly find it easier to give examples than to speak!) . string provides many functions to insert, erase, replace, and add characters. Let's start with increment characters (here we're talking about increment on the tail), and the functions are +=, append(), push_back().

Examples are as follows:

s+=str; // Add a string s+= "my name is jiayp"; // Add a C string s+='a'; // Add the character s.append(str); S.a ppend (STR, 1, 3); // Does not explain s.append(str,2,string::npos)// does not explain s.append(" my name is jiayp "); s.append(“nico”,5); s.append(5,'x'); s.push_back(‘a'); // This function can only add a single character to the STL familiar understanding is simple

If you need to insert a string somewhere in the middle of a string, you can use the insert() function, which requires you to specify an index of the insert position, and the inserted string will be placed behind this index.

 s.insert(0,”my name”);
 s.insert(1,str);

This form of insert() does not support passing in a single character, which must be written as a string (which is disgusting). Now that you're sick, you have to read the following paragraph: In order to insert a single character, the insert() function provides two overloaded functions for inserting a single character: insert(size_type index,size_type num,chart c) and insert(iterator pos,size_type num,chart c). Where size_type is an unsigned integer and iterator is char*, so you can't call insert like this: insert(0,1, 'j'); What is the first parameter converted to? So you have to write this: insert((string::size_type)0,1, 'j')! The second form refers to the use of iterators to interpolate characters, which will be mentioned later. By the way, string uses STL iterators for many operations, and it tries to be as close to STL as possible.

The delete function erase() can take several forms (annoying!). The replace() function also has several functions.

For example:

string s=”il8n”; S.r eplace nternationalizatio (1, 2, ""); // Replace the 2 from index 1 with C_string s.ase (13); // Delete all S.ASE (7,5) from index 13 onwards; // Delete 5 from index 7 onwards

2.6 Extracting substring and string connections

The function to retrieve a substring is: substr(), of the form:

s.substr(); // Return the full contents of s.sbstr (11); // substring s.ubstr (5,6) from index 11; // 6 characters from index 5

The function that combines two strings is +. (Anyone who does not understand please call 120)

2.7 I/O Operations

1. >> Read a string from the input stream. 2. << Writes a string to the output stream. Another function is getline(), which reads a line from the input stream until it encounters a line character or reaches the end of the file.

2.8 Search and lookup

There are many powerful search functions, including: find() rfind() find_first_of() find_last_of() find_first_not_of() find_last_not_of() find_first_not_of() find_last_not_of()

These functions return the index of the first character in the range of characters that match the search criteria, and return npos if the target is not found. The parameters of all functions are described as follows: The first parameter is the object to be searched. The second parameter (optional) indicates the search starting index in string, and the third parameter (optional) indicates the number of characters to search. Relatively simple, do not say do not understand can put forward to me, I then carefully answer. Of course, the more powerful STL search will be mentioned later.

Finally, to talk about the meaning of npos, string::npos type is string::size_type, so once you need to compare an index to npos, the index value must be string::size)type, more often, We can compare the function directly to npos (e.g. if(s.ind (" jia ")== string::npos)).

Constructor of the string class:

string(const char *s); // Initialize string(int n,char c) with c string s; // Initialized with n characters c In addition, the string class also supports default constructors and copy constructors, such as string s1; string s2="hello"; It's all written correctly. length_error is raised when the constructed string is too long to express

string class character operations:

const char &operator[](int n)const; const char &at(int n)const; char &operator[](int n); char &at(int n); Both operator[] and at() return the position of the NTH character in the current string, but the at function provides range checking and throws an out_of_range exception when the bounds are crossed, and the subscript operator[] does not provide check access. const char *data()const; // Returns a non-null-terminated c character array const char *c_str()const; // Returns a null-terminated c string int copy(char *s, int n, int pos = 0) const; // Copies the n characters in the current string starting with pos into the character array starting with s, and returns the actual number of copies

Feature description of string:

int capacity()const; // Returns the current capacity (that is, the number of elements in string that can be stored without adding memory) int max_size()const; // Mandatory string Length of the maximum string that can be stored in the object int size()const; // Returns the size of the current string int length()const; // Returns the length of the current string bool empty()const; // Whether the current string is empty void resize(int len,char c); // Set the current size of the string to len and fill in the missing part with the character c

Input/output operations of the string class:

The string class overloads operator>> for input and operator<< for output operations. Function getline(istream&in, string&s); Used to read strings from input stream in into s, separated by newline '\n'.

string assignment:

string &operator=(const string &s); // assign the string s to the current string string&assign (const char *s); // assign string &assign(const char *s,int n) with the c type string s; // assign string &assign(const string &s) to n characters starting with c string s; // assign the string s to the current string string string &assign(int n,char c); // assign n characters c to the current string string&assign (const string&s,int start,int n); // assign n characters from the string s starting with start to the current string string string &assign(const_iterator first,const_itertor last); // Assign the part between the first and last iterators to the string

string connection:

string &operator+=(const string &s); // Concatenate the string s to the end of the current string string &append(const char *s); // Concatenate the c string s to the end of the current string string &append(const char *s,int n); // Concatenate the first n characters of the c type string s to the end of the current string string string &append(const string&s); // Same as operator+=() string &append(const string &s,int pos,int n); // Concatenate n characters in string s starting from pos to the end of the current string string &append(int n,char c); // Add n characters to the end of the current string c string &append(const_iterator first,const_iterator last); // Concatenates the part between the iterators first and last to the end of the current string

string comparison:

bool operator==(const string &s1,const string &s2)const; // Compares whether two strings are equal operators ">","<",">=","<=","! =" is overloaded for string comparison; int compare(const string &s) const; // compare the size of the current string with s int compare(int pos, int n,const string &s)const; // compare the size of the current string consisting of n characters starting from pos with s int compare(int pos, int n,const string &s,int pos2,int n2)const; // compare the size of the current string consisting of n characters starting from pos with the size of the string consisting of n2 characters starting from pos2 in s int compare(const char *s) const; int compare(int pos, int n,const char *s) const; int compare(int pos, int n,const char *s, int pos2) const; compare returns 1 for >, -1 for <, and 0 for ==

Substring of string:

string substr(int pos = 0,int n = npos) const; // Returns the n-character string at the beginning of pos

string exchange:

void swap(string &s2); // Swap the value of the current string with s2

Lookup function of the string class:

int find(char c, int pos = 0) const; // Start from pos to find the position of character c in the current string int find(const char *s, int pos = 0) const; // Start from pos to find the position of the string s in the current string int find(const char *s, int pos, int n) const; // Starting from pos, find the position of the first n characters in the string s in the current string int find(const string &s, int pos = 0) const; // Start from pos to find the position of the string s in the current string // If the search succeeds, the position is returned. If the search fails, string::npos value int rfind(char c, int pos = npos) const; // Find the position of character c in the current string from the back to the front starting from pos int rfind(const char *s, int pos = npos) const; int rfind(const char *s, int pos, int n = npos) const; int rfind(const string &s,int pos = npos) const; // Starting from pos, search for the position of the string consisting of the first n characters in the string s. The position is returned if the string succeeds. If the string fails, string::npos value int find_first_of(char c, int pos = 0) const; // Find the first occurrence of the character c from pos int find_first_of(const char *s, int pos = 0) const; int find_first_of(const char *s, int pos, int n) const; int find_first_of(const string &s,int pos = 0) const; // Starting from pos, find the position of the first character in the current string in the array of the first n characters of s. Search failure Mandatory string::npos int find_first_not_of(char c, int pos = 0) const; int find_first_not_of(const char *s, int pos = 0) const; int find_first_not_of(const char *s, int pos,int n) const; int find_first_not_of(const string &s,int pos = 0) const; // Search for the position of the first character in the current string that is not in the string s, failed string::npos int find_last_of(char c, int pos = npos) const; int find_last_of(const char *s, int pos = npos) const; int find_last_of(const char *s, int pos, int n = npos) const; int find_last_of(const string &s,int pos = npos) const; int find_last_not_of(char c, int pos = npos) const; int find_last_not_of(const char *s, int pos = npos) const; int find_last_not_of(const char *s, int pos, int n) const; int find_last_not_of(const string &s,int pos = npos) const; //find_last_of and find_last_not_of are similar to find_first_of and find_first_not_of, but look from the back

Substitution function of the string class:

string &replace(int p0, int n0,const char *s); // Delete n0 characters starting from p0, then insert the string s string &replace(int p0, int n0,const char *s, int n) at p0; // Remove n0 characters starting with p0, then insert the first n characters of string s at p0 string&replace (int p0, int n0,const string&s); // Delete n0 characters starting from p0 and insert the string s string&replace (int p0, int n0,const string&s, int pos, int n) at p0; // Delete n0 characters starting with p0, then insert n characters starting with pos in the string s at p0 string&replace (int p0, int n0,int n, char c); // Delete n0 characters starting with p0 and insert n characters at p0 c string &replace(iterator first0, iterator last0,const char *s); // replace(iterator first0, iterator last0,const char *s, int n) with the string s string&replace (iterator first0, iterator last0,const char *s, int n); // Replace (iterator first0, iterator last0,const string&replace (iterator first0, iterator last0,const string&s); // replace(iterator first0, iterator last0,int n, char c) with the string s string &replace(iterator first0, iterator last0,int n, char c); // put [first0, c string &replace(iterator first0, iterator last0,const_iterator first, const_iterator last); // Replace the part between [first0, last0) with the string between [first, last)

Insert function of string class:

string &insert(int p0, const char *s); string &insert(int p0, const char *s, int n); string &insert(int p0,const string &s); string &insert(int p0,const string &s, int pos, int n); // The first 4 functions insert the first n characters starting with pos in string s at p0: string &insert(int p0, int n, char c); // This function inserts n characters at p0 c iterator insert(iterator it, char c); void insert(iterator it, const_iterator first, const_iterator last); // Insert the character c at it, returning the position of the iterator; void insert(iterator it, int n, char c) between [first, last] at it;// Insert n characters c at it

Delete function of the string class

iterator erase(iterator first, iterator last); // Delete all characters between [first, last), returning the location of the iterator after deletion. iterator erase(iterator it); // Delete the character pointed to by it, returning the position of the deleted iterator string &erase(int pos = 0, int n = npos);// Delete the n characters starting from pos, returning the modified string

Iterator handling of the string class:

The string class provides an iterator that traverses forward and backward. Iterators provide syntax for accessing individual characters, similar to pointer operations, and iterators do not check ranges.

Declare the iterator variable with string::iterator or string::const_iterator. const_iterator does not allow you to change the contents of the iteration. Common iterator functions are const_iterator begin()const; iterator begin(); // Mandatory string start position const_iterator end()const; iterator end(); // Mandatory string position after the last character const_iterator rbegin()const; iterator rbegin(); // Mandatory string position of the last character const_iterator rend()const; iterator rend(); // Mandatory string rbegin and rend before the first character position are used for backward iterative access by setting the iterators string::reverse_iterator,string::const_reverse_iterator

String stream processing:

This is done by defining the ostringstream and istringstream variables in the <sstream> header file

For example:

string input("hello,this is a test"); istringstream is(input); string s1,s2,s3,s4; is>>s1>>s2>>s3>>s4; //s1="hello,this",s2="is",s3="a",s4="test" ostringstream os; os<<s1<<s2<<s3<<s4; cout<<os.str();

To this article about the use of string in c++ common function summary of the article is introduced to this, more related to string common function content please search the script home previous articles or continue to browse the following related articles hope that you will support the script home in the future!

Related article

  • C语言实现简单的通讯录

    C language to achieve a simple address book

    This article mainly introduces the C language to achieve a simple address book in detail, the example code in the article is very detailed, has a certain reference value, interested partners can refer to it
    2018-02-02
  • 解析使用C++编写无错代码的方法技巧

    Analyze method tips for writing error-free code in C++

    This article is a detailed analysis of the method of using C++ to write error-free code, the need for friends to refer to
    2013-05-05
  • C++中的复制构造函数详解

    Details of the copy constructor in C++

    Today, Xiaobian will share an article about the implementation of C++ copy constructor, Xiaobian feel that the content is very good, now share with you, has a good reference value, need friends to follow Xiaobian to see
    2021-09-09
  • Java C++ 算法题解leetcode1608特殊数组特征值

    Java C++ algorithm to solve leetcode1608 special array eigenvalues

    This article mainly introduces the Java C++ algorithm problem expansion leetcode1608 special array feature value example detailed solution, friends in need can use for reference, I hope to be helpful, I wish you a lot of progress, early promotion and pay rise
    2022-09-09
  • MoveWindow() SetWindowPos()的区别于联系

    MoveWindow() SetWindowPos() is different from contact

    This article mainly introduces the difference between VC++ MoveWindow() SetWindowPos() and contact, need friends can refer to the next
    2015-01-01
  • C语言全部内存操作函数的实现详细讲解

    C language all memory operation function implementation detailed explanation

    This article mainly introduces the implementation of all the C language memory operation functions in detail, the author explained with graphic code examples is very clear, interested students can study
    2021-02-02
  • C语言实现冒泡排序算法的示例详解

    C language to implement bubble sort algorithm example detailed explanation

    This article mainly introduces how to achieve the C language bubble sorting algorithm, the article introduces very detailed through the example code, which has certain reference value for everyone's study or work, and the friends who need to study together with Xiaobian below
    2022-04-04
  • C语言简易实现扫雷小游戏

    C language simple minesweeping game

    This article mainly introduces in detail the simple implementation of the C language minesweeper game, the example code in the article is very detailed, has a certain reference value, interested partners can refer to it
    2021-10-10
  • KMP 算法实例详解

    KMP algorithm example details

    This article mainly introduces the KMP algorithm example detailed information,MP the key is to find the value of next, preprocess the value of next first, the need of friends can refer to the next
    2017-07-07
  • 详解在VScode中添加代码块(含C++指令生成代码)

    Add code blocks to VScode (including C++ instruction generation code)

    This article mainly introduces the detailed explanation in VScode to add code blocks (including C++ instruction generation code), the article through the example code is very detailed, for everyone's study or work has a certain reference learning value, the need for friends to study together with the small series below
    2021-04-04

Latest comments