当前位置:网站首页>String (explanation)
String (explanation)
2022-07-07 06:33:00 【Korean suspense】
Catalog
1. From the standard library string Class understanding
- string Is a string class that represents a string
- 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 .
- 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 )
- 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 
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 
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 
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 
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 
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 
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 
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
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 
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 
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
边栏推荐
- 2022 Android interview essential knowledge points, a comprehensive summary
- JWT 认证
- HKUST & MsrA new research: on image to image conversion, fine tuning is all you need
- Software testing knowledge reserve: how much do you know about the basic knowledge of "login security"?
- Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
- Force deduction 62 different paths (the number of all paths from the upper left to the lower right of the matrix) (dynamic planning)
- 哈趣投影黑馬之姿,僅用半年强勢突圍千元投影儀市場!
- VMware安装后打开就蓝屏
- How to set up in touch designer 2022 to solve the problem that leap motion is not recognized?
- Calculation model FPS
猜你喜欢

一段程序让你明白什么静态内部类,局部内部类,匿名内部类

【OpenCV】形态学滤波(2):开运算、形态学梯度、顶帽、黑帽

693. Travel sequencing

string(讲解)

Experience sharing of contribution of "management world"

HKUST & MsrA new research: on image to image conversion, fine tuning is all you need

MySQL installation

面试中有哪些经典的数据库问题?

缓存在高并发场景下的常见问题

JMeter's own functions are not enough? Why don't you develop one yourself
随机推荐
软件测试到了35岁,真的就干不动了吗?
string(讲解)
Test the foundation of development, and teach you to prepare for a fully functional web platform environment
JWT 认证
[solution] final app status- undefined, exitcode- 16
dolphinscheduler3.x本地启动
3531. Huffman tree
c语言(结构体)定义一个User结构体,含以下字段:
c语言面试写一个函数在字符串N中查找第一次出现子串M的位置。
Basic DOS commands
「运维有小邓」符合GDPR的合规要求
POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
Learning notes | data Xiaobai uses dataease to make a large data screen
Postgresql中procedure支持事务语法(实例&分析)
蚂蚁庄园安全头盔 7.8蚂蚁庄园答案
Ha Qu projection dark horse posture, only half a year to break through the 1000 yuan projector market!
ceres-solver和g2o性能比较
LM小型可编程控制器软件(基于CoDeSys)笔记二十三:伺服电机运行(步进电机)相对坐标转换为绝对坐标
如何解决数据库插入数据显示SQLSTATE[HY000]: General error: 1364 Field ‘xxxxx‘ doesn‘t have a default value错误
Ant manor safety helmet 7.8 ant manor answer