Elementary level of C++ - string (character array), say goodbye to the cumbersome design in C language

Preface: In daily programming, we often use strings. For example, a person's ID number, home address, etc. can only be represented by strings. In C language, we often use character arrays to store strings, but it is cumbersome to operate in certain scenarios (such as insertion, deletion). In C++, a string class is designed at the bottom layer to encapsulate frequently used functions. It is very simple and convenient to use.
This article mainly introduces the use of string and several common functions, and finally lists some classic examples.
When we use string, we often use the functions it encapsulates. Here is a website recommended: C++ Reference . You can refer to this website if you forget how to use the function.

1. Introduction

To make a long story short, without making it too mysterious:
string is a class implemented as a sequential array of characters, used to manage character arrays.
How we usually use custom classes is how we use string.

Two. Use

1. Create a character array to store the string hello world:

Format: string 对象("字符或字符串")
1. The form is like string str2("hello world"), in fact, it is to call the constructor of the string class to initialize the object str2.
2. There are stream extraction stream insertion operators overloaded in the string class, which can directly output or output string type data.

//C语言
char str1[] = "hello world";
//C++
string str2("hello world"); //构造函数
string str3("#");  //单个字符
cout << str2 << endl; //string类中有流提取流插入运算符重载,可以直接输出或者输出string类型数据。

The console output is as follows:
Insert image description here

2. Intercept part of the string

The string class is also designed for this: the first parameter is to intercept the string object, the second is the starting subscript of the part to be intercepted, and the third parameter is the number of characters to be intercepted (in bytes);
Insert image description here

The following code: I want to intercept the world in the s1 object and give it to s2, the subscript of w is 6 (the second parameter), and the world has 5 characters (the third parameter)

int main()
{
    
    
	string s1("hello world");
	string s2(s1, 6, 5); //截取s1对象中的world给给s2
	cout << s2 << endl;
}

The console output is as follows, you can see that the interception was successful:
Insert image description here

3. Input from the keyboard

Here we can reflect the advantages of string:
using C language, we need to consider how much space to open for the character array, but string does not need us to consider this point, we just input, the compiler will automatically help us adapt the appropriate space.

int main()
{
    
    
	string s1; //实例化一个对象s1
	cin >> s1; // 输入
	cout << s1 << endl; //打印
	return 0;
}

As follows: the first two lines are input from the keyboard, and the last two lines are printed.
Insert image description here

3. Commonly used overloaded operators and functions

The interface designed by the string function, if you are interested, you can go to the website given at the beginning of the article. Some of the following functions only give commonly used interfaces.

1.+/+=

From this topic alone, you can feel the charm of string!

Please see the topic: Input two strings from the keyboard, and ask to splice the latter string to the back of the previous string, and output the spliced ​​previous string. (The length of the string does not exceed 50 bytes)
From the perspective of C language: first we need to open two character arrays of no less than 50 bytes, and then the simpler thing is to use the strcat function to splice. But the strcat function has not been used for a long time, I have forgotten it, and I have to look through the notes again.

The C++string class is +运算符overloaded, and the essence of this + is tail insertion

int main()
{
    
    
	string s1, s2;
	cin >> s1 >> s2;
	s1 = s1 + s2;  //s1,s2顺序不能颠倒
	//s1 += s2; //使用+=也可以
	cout << s1 << endl;
	return 0;
}

The console output is as follows: the first line is the input s1, the second line is the input s2, and the third line is the spliced ​​s1
Insert image description here

2.size()

Returns the effective character length of the string object (excluding \0), which is equivalent to strlen in C language.

int main()
{
    
    
	string s1("hello world");
	cout << s1.size() << endl;
	return 0;
}

The console output is as follows:
Insert image description here

3.capacity()

Returns the capacity of the string object.
We know that string will automatically expand, and of course it is not byte wide. It expands according to a certain ratio.

int main()
{
    
    
	string s1("hello world");
	cout << "size:" << s1.size() << endl;
	cout << "capacity:" << s1.capacity() << endl;
	return 0;
}

The console output is as follows: You can see that the effective character size is 11 bytes and the capacity is 15 bytes.
Insert image description here

4.reserve()

reserve——Reserve (don't think of it as reverse)
Function: Request capacity change
Value: If you determine how much space you need to open, you can open it in advance to reduce capacity expansion and improve efficiency. (Expansion comes at a cost, especially off-site expansion, which requires copying data from the old space to the new space)

int main()
{
    
    
	string s1("hello world");
	cout << "size:" << s1.size() << endl;
	cout << "原capacity:" << s1.capacity() << endl;
	s1.reserve(100);
	cout << "新capacity:" << s1.capacity() << endl;
	return 0;
}

The console output is as follows:
Insert image description here

5.[] operator (traverse string)

The string class overloads the [] operator so that we can use [] to access strings like accessing arrays. It is very helpful for solving some problems related to strings.

Take traversing string as an example:

int main()
{
    
    
	string s1("hello world");
	for (size_t i = 0; i < s1.size(); i++) //运用size()函数
	{
    
    
		cout << s1[i] << " ";  //下标访问
	}
	return 0;
}

The console output is as follows:
Insert image description here

6.push_back() (insert a character at the end)

Insert a character at the end of the string object

int main()
{
    
    
	string s1("hello world");
	s1.push_back('x');
	cout << s1 << endl;
	return 0;
}

The console output is as follows:
Insert image description here

7.append() (insert a string at the end)

Form: append (string/string object)
is actually somewhat redundant in design, we can just use += for insertion, why use the append function again?

int main()
{
    
    
	string s1("hello world");
	string s2("!!!");
	s1.append("xxx");
	s1.append(s2);
	cout << s1 << endl;
	return 0;
}

The console output is as follows:
Insert image description here

8.insert() (head insertion)

Insert a character:
1. Conventional method: s.insert (start position subscript, insert number, character to be inserted)
2. Iterator method: s.insert(s.begin(), character to be inserted)

int main()
{
    
    
	string s1("hello world");
	string s2("hello world");
	string s3("hello world");
	s1.insert(1,1,'x'); // 在h后插入一个x
	s2.insert(1, 2, 'x'); // 在h后插入两个x 
	s3.insert(s3.begin(), 'x'); // 头插x 
	cout << "s1 = " << s1 << endl;  //hxello world
	cout << "s2 = " << s2 << endl;  //hxxello world
	cout << "s3 = " << s3 << endl;  //xhello world
	return 0;
}

Insert a string: s.insert (starting position subscript, string)

int main()
{
    
    
	string s1("hello world");
	s1.insert(1,"xx");
	cout << s1 << endl; //hxxello world
	return 0;
}

Four. Iterator

1.iterator Forward iterator (emphasis)

Function name Function (the following function only applies to forward iterators!!!)
begin() Returns the address at the beginning of string
end() Returns the address of the next position of the last valid character of string (usually \0)

Iterator means iterator, which is encapsulated in the string class (there are iterators in data structures such as list, tree, etc.), so it must be restricted by the string class domain when using it, and it must be written as a form string::iterator. It can be understood as a pointer when used.

Traverse the string with the help of iterators:

int main()
{
    
    
	string s1("hello world");
	string::iterator str = s1.begin();
	//auto str = s1.begin(); 写成这样也可以,auto是类型指示符,可以根据begin推出正向迭代器
	while (str != s1.end())  
	{
    
    
		cout << *str << " ";
		++str;
	}
	cout << endl;
	return 0;
}

The console input is as follows:
Insert image description here

Insert image description here
The above code uses the begin() function to return the iterator of the start position, and end() points to the next position of the last character (here is \0).

Question: But isn’t this just a simple pointer traversal? Why bother using an iterator?
Answer: One of the characteristics of iterators is their versatility. There are iterators in vectors, lists, trees, etc. Take the list as an example. It is composed of small nodes one by one. The physical space is not continuous. Using the node pointer ++ cannot find its next node, but it is easy to use an iterator like the above code You can traverse the list. Therefore, iterator traversal is the most mainstream traversal method.

2.reverse_iterator reverse iterator

Function name Role (the following functions are only applicable to reverse iterators!!!)
rbegin() Returns the address of the next position of the last valid character of string (usually \0)
rend() Returns the address at the beginning of string

As the name implies, reverse_iterator is used anyway, contrary to forward iterator.

Traverse the string backwards with the help of a reverse iterator:

int main()
{
    
    
	string s1("hello world");
	string::reverse_iterator str = s1.rbegin();
	//auto str = s1.rbegin(); 写成这样也可以,auto是类型指示符,可以根据rbegin推出反向迭代器
	while (str != s1.rend())
	{
    
    
		cout << *str << " ";
		++str;
	}
	cout << endl;
	return 0;
}

The console input is as follows, you can see that it traverses backwards:
Insert image description here

Supplement: const iterator: const_iterator const_reverse_iterator
There are 4 types of iterators in total.

3.reverse function (string reverse artifact)

Pass in the iterator range: reverse(s.begin(),s.end());

int main()
{
    
    
	string s1("hello world");
	reverse(s1.begin(), s1.end()); //传入迭代器区间
	cout << s1 << endl;
	return 0;
}

The console output is as follows:
Insert image description here

5. Example questions

1. Add strings

click the link

High precision, cannot be added directly using integers or long integers.
Use string to add bit by bit and carry.

class Solution {
    
    
public:
    string s;
    string addStrings(string num1, string num2) {
    
    
        int end1 = num1.size()-1,end2 = num2.size()-1;
        int ret = 0,sum = 0;
        while(end1 >= 0 || end2 >= 0)
        {
    
    
            int n1 = end1>=0?num1[end1]-'0':0;
            int n2 = end2>=0?num2[end2]-'0':0;
            sum = n1+n2+ret;
            ret = sum/10;
            s += sum%10+'0';
            --end1;
            --end2;
        }
           if(ret == 1)
              s += '1';
        reverse(s.begin(),s.end());
        return s;
    }
};

2. The length of the last word of the string

1. Niuke needs to include the header file < string >
2. If rfind() is not found, return unsigned -1
3. string::npos == unsigned -1
4. Pay attention to the case of only one word

#include <iostream>
#include<string>
using namespace std;
int main()
{
    
    
    string s1;
    getline(cin,s1);
    size_t eblack = s1.rfind(' '); //倒着找第一个空格,没找到返回无符号的-1
    if(eblack != string::npos)
    {
    
    
        cout << s1.size()-(1+eblack); //下标-1
    }
    else {
    
    
        cout << s1.size();
    }
    return 0;
}

3. Reverse a word in a string III

click the link

Using the iterator reverse function

class Solution {
    
    
public:
    string reverseWords(string s) {
    
    
    int i = 0,k = 0;
    while(s[i]!='\0')
    {
    
    
        if(s[i] == ' ') //找空格
        {
    
    
            reverse(s.begin()+k,s.begin()+i); //借助reverse反转单词
            k = i + 1;
        }
        i++;
    }
    reverse(s.begin()+k,s.end()); //反转仅有或仅剩一个单词的情况
    return s;
    }
};

BB at the end of the article: For friends who have any questions, feel free to leave a message in the comment area. If there are any questions, friends are welcome to point out in the comment area. The blogger will confirm the modification as soon as possible after seeing it. Finally, it is not easy to make. If it is helpful to friends, I hope to give the blogger some likes and attention.
Insert image description here

Guess you like

Origin blog.csdn.net/qq_73390155/article/details/132393949