当前位置:网站首页>String (explanation)

String (explanation)

2022-07-07 06:33:00 Korean suspense

1. From the standard library string Class understanding

  1. string Is a string class that represents a string
  2. The interface of this class is basically the same as that of a regular container , And added some special operations for string General operation of .
  3. string At the bottom, it's actually :basic_string Alias of template class ,typedefbasic_string<char, char_traits, allocator>string;( The wrong report is basic_string Don't pay too much attention )
  4. Cannot manipulate sequences of multibyte or variable length characters . In the use of string Class time , Must contain #include Header files and using namespace std;

2.sting Common constructor usage

#include<string>

// Manage dynamically growing character arrays , With \0 For the end 
int main()
{
    
	string s1;
	return 0;
}

This is the most commonly used , The function is to manage the dynamically growing character array , With \0 For the end .
But note that the compilation cannot succeed here
Because in use string Class time , Must contain #include Header files and using namespace std;( because c++ Standard libraries are stored in std Inside )

If you don't pack std, You can use it as follows
Code

#include<string>

// Manage dynamically growing character arrays , With \0 For the end 
int main()
{
    
	std::string s1;
	return 0;
}

But of course , Here we put... For convenience std Expand all
string There's another way to write it , Namely

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

// Manage dynamically growing character arrays , With \0 For the end 
int main()
{
    
	string s1;
	string s2("hello world");
	return 0;
}

This is initialized with constant strings , This use new perhaps malloc Coming out , Then copy this array , The biggest advantage of this is that it grows dynamically , If you make an array, its size is fixed , however string This can grow dynamically , The principle is also simple , Because it is capacity expansion
usage

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

// Manage dynamically growing character arrays , With \0 For the end 
int main()
{
    
	string s1;
	string s2("hello world");
	s2 += "!!!!!";
	cout<<s2<<endl;
	return 0;
}

Print the results
 Insert picture description here
But of course, in addition to this, there is also a copy structure
Code

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

// Manage dynamically growing character arrays , With \0 For the end 
int main()
{
    
	string s1;
	string s2("hello world");
	s2 += "!!!!!";
	cout << s2 << endl;

	string s3(s2);
	string s4 = s2;
	return 0;
}

Just take an object that exists , To initialize a nonexistent object , This is all copy construction

There's another way to write it , Just want to use this string before n To initialize , Don't do it in the back
Code

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

// Manage dynamically growing character arrays , With \0 For the end 
int main()
{
    
	string s1;
	string s2("hello world");
	s2 += "!!!!!";
	cout << s2 << endl;

	string s3(s2);
	string s4 = s2;
	string s5("https://editor.csdn.net/md?articleId=125475746", 4);
	cout << s5 << endl;
	return 0;
}

Running results
 Insert picture description here

Another is from a string n Start with position , Copy n Characters
Code

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

// Manage dynamically growing character arrays , With \0 For the end 
int main()
{
    
	string s1;
	string s2("hello world");
	s2 += "!!!!!";
	cout << s2 << endl;

	string s3(s2);
	string s4 = s2;
	string s5("https://editor.csdn.net/md?articleId=125475746", 4);
	cout << s5 << endl;
	string s6(s2, 5, 6);
	cout << s6 << endl;
	return 0;
}

Running results
 Insert picture description here
But here if I only want 6 individual , If I want 100 Can you report an error ?
The answer is no , If you exceed the size of the string, give as much as you want

3.string Small exercise

We put string Let's do the next question
Question link

Title Description
Give you a string s , Reverse the string according to the following rules :

All non English letters remain in their original positions .
All English letters ( Lowercase or uppercase ) Position reversal .
Returns the inverted s .

But of course, the most important thing to do this problem is to traverse the string
Not mentioned before string Traversal of

The code of the first traversal method
1. Subscript +[]

void test2()
{
    
	string s1("hello");
	cout << s1.size() << endl;// This does not include \0 Of 

	// The first way   Subscript +[]
	for (size_t i = 0; i < s1.size(); i++)
	{
    
		//s1.operator[](i);
		cout << s1[i] << " ";
	}
	cout << endl;
}

This should be noted here size It doesn't include \0 So the printing is 5 individual , And the traversal method is also different. This is not an array , This is equivalent to calling a function , Equivalent to calling s1.operator;

Running results
 Insert picture description here

The second way to traverse
2. iterator

void test3()
{
    
	string s1("hello");
	// iterator 
	string::iterator it=s1.begin();
	while (it != s1.end())
	{
    
		cout << *it << " ";
		++it;
	}
	cout << endl;
}

This is iterator traversal , Iterators are things like pointers, or pointers ,s1.begjn() It represents the starting position , and end() Is the next position that represents the end , In fact, it's left closed and right open .
There is also a question whether we can put it != s1.begin() Change to it < s1.begin(), stay 1 Some situations can , For example, their space is continuous , But not recommended < This way of writing , Because your memory is not necessarily continuous , Once it is not continuous, you will make mistakes

Running results
 Insert picture description here

The third way of traversal

void test4()
{
    
	string s1("hello");
	for (auto ch :  s1)
	{
    
		cout << ch << " ";
	}
}

3. Range for
The principle is simple , In fact, the underlying principle is to replace it with iterators

Running results
 Insert picture description here
Question answer
Subscript +[] Writing

class Solution {
    
public:
    bool isLetter(char ch)
    {
    
        // As long as it is 26 Bit letters return true 
        if( ch >='a' && ch<='z')
              return true;
        else if(ch>='A' && ch<='Z')
              return true;
        else
              return false;
    }
    string reverseOnlyLetters(string s) {
    
        int left=0,right=s.size()-1; 
        while(left<right)
        {
    
        // yes 26 Letters don't move , Direct exchange , If not, add and subtract as required 
            while(left<right && !isLetter(s[left]))
                 ++left;
            while(left<right && !isLetter(s[right]))
                 --right;
            swap(s[left],s[right]);
            ++left;
            --right;
        }
        return s;
    }
};

How to write iterators
Code

class Solution {
    
public:
    bool isLetter(char ch)
    {
    
        if( ch >='a' && ch<='z')
              return true;
        else if(ch>='A' && ch<='Z')
              return true;
        else
              return false;
    }
    string reverseOnlyLetters(string s) {
    
        string::iterator leftit=s.begin();
        string::iterator rightit=s.end()-1; 
        while(leftit<rightit)
        {
    
            while(leftit<rightit && !isLetter(*leftit))
                 ++leftit;
            while(leftit<rightit && !isLetter(*rightit))
                 --rightit;
            swap(*leftit,*rightit);
            ++leftit;
            --rightit;
        }
        return s;
    }
};

4. iterator

1. Forward iterator

This is very simple. The iterator that traverses the string mentioned above is the forward iterator
Code

void test3()
{
    
	string s1("hello");
	// iterator 
	string::iterator it=s1.begin();
	while (it != s1.end())
	{
    
		cout << *it << " ";
		++it;
	}
	cout << endl;
}

2. reverse iterator

This is the same as the name , Forward traversal is traversal from the front , Then reverse traversal starts from the back
Code

void test5()
{
    
	string s1("hello");
	string::reverse_iterator rit = s1.rbegin();
	while (rit!=s1.rend())
	{
    
		cout << *rit << " ";
		++rit;
	}
	cout << endl;;
}

Running results
 Insert picture description here

3. added const The iterator

Code

void test3()
{
    
	string s1("hello");
	// iterator 
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
    
		(*it) += 1;
		cout << *it << " ";
		++it;
	}
	cout << endl;

	it = s1.begin();
	while (it != s1.end())
	{
    
		(*it) -= 1;
		cout << *it << " ";
		++it;
	}
	cout << endl;
}


// Manage dynamically growing character arrays , With \0 For the end 
int main()
{
    
	test3();
	return 0;
}

Because iterators are things like pointers or pointers , So he can read and write
Here are the results , The above code means to let hello every -1, And then by adding 1 Come back hello
 Insert picture description here
So the normal version here , With this version, there are also const Version of the
const The version of can only be read , Can't write
Code
 Insert picture description here
You can see that there are not only two iterators, but actually four , Forward iterator ,const Forward iterator , reverse iterator ,const reverse iterator

But of course, some people may think that iterators are too troublesome to type so much code , At this time, there is a good way
That's it auto
Code
 Insert picture description here

5.string Of swap And in the Library swap The difference between

Code

#include<iostream>
using namespace std;


void test1()
{
    
	string s1("hello world");
	string s2("hello");
	s1.swap(s2);
	swap(s1, s2);
}

int main()
{
    
	test1();
	return 0;
}

What is the difference between them
s1.swap(s2); It is efficient because it exchanges two pointers
swap(s1, s2); Because it is a deep copy

原网站

版权声明
本文为[Korean suspense]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070145266080.html