当前位置:网站首页>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
- docker-compose启动redis集群
- VMware安装后打开就蓝屏
- JVM in-depth
- Force deduction 62 different paths (the number of all paths from the upper left to the lower right of the matrix) (dynamic planning)
- [FPGA] EEPROM based on I2C
- vim映射大K
- Redis (I) -- getting to know redis for the first time
- Three updates to build applications for different types of devices | 2022 i/o key review
- C语言整理(待更新)
猜你喜欢
MySQL的安装
Audio distortion analysis of DSP and DAC based on adau1452
Find duplicate email addresses
Force deduction 62 different paths (the number of all paths from the upper left to the lower right of the matrix) (dynamic planning)
软件测试到了35岁,真的就干不动了吗?
Redis (I) -- getting to know redis for the first time
Apache ab 压力测试
Redis (II) - redis General Command
FlexRay通信协议概述
Experience sharing of contribution of "management world"
随机推荐
dolphinscheduler3.x本地启动
go-microservice-simple(2) go-Probuffer
ETCD数据库源码分析——从raftNode的start函数说起
Wechat applet hides the progress bar component of the video tag
Niuke Xiaobai monthly race 52 E. sum logarithms in groups (two points & inclusion and exclusion)
C language interview to write a function to find the first occurrence of substring m in string n.
Three updates to build applications for different types of devices | 2022 i/o key review
When we talk about immutable infrastructure, what are we talking about
计算模型 FPS
vim映射大K
Unity C# 函数笔记
Postgresql源码(60)事务系统总结
哈趣投影黑馬之姿,僅用半年强勢突圍千元投影儀市場!
MySQL卸载文档-Windows版
Array proof during st table preprocessing
基于FPGA的VGA协议实现
Ha Qu projection dark horse posture, only half a year to break through the 1000 yuan projector market!
dolphinscheduler3. X local startup
The difference between string constants and string objects when allocating memory
ICML 2022 | 探索语言模型的最佳架构和训练方法