当前位置:网站首页>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
边栏推荐
- 3428. Put apples
- MySQL卸载文档-Windows版
- PostgreSQL database timescaledb function time_ bucket_ Gapfill() error resolution and license replacement
- docker-compose启动redis集群
- ceres-solver和g2o性能比较
- Postgresql源码(59)分析事务ID分配、溢出判断方法
- [opencv] morphological filtering (2): open operation, morphological gradient, top hat, black hat
- 力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)
- LM small programmable controller software (based on CoDeSys) Note 23: conversion of relative coordinates of servo motor operation (stepping motor) to absolute coordinates
- JWT certification
猜你喜欢
Redis (II) - redis General Command
Doctoral application | Professor Hong Liang, Academy of natural sciences, Shanghai Jiaotong University, enrolls doctoral students in deep learning
[SOC FPGA] peripheral PIO button lights up
Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
A program lets you understand what static inner classes, local inner classes, and anonymous inner classes are
win系统下安装redis以及windows扩展方法
【从零开始】win10系统部署Yolov5详细过程(CPU,无GPU)
Ideas of high concurrency and high traffic seckill scheme
go-microservice-simple(2) go-Probuffer
当前发布的SKU(销售规格)信息中包含疑似与宝贝无关的字
随机推荐
JMeter function assistant - random value, random string, fixed value random extraction
JWT certification
[solution] final app status- undefined, exitcode- 16
哈趣投影黑馬之姿,僅用半年强勢突圍千元投影儀市場!
[SOC FPGA] peripheral PIO button lights up
tkinter窗口选择pcd文件并显示点云(open3d)
c面试 加密程序:由键盘输入明文,通过加密程序转换成密文并输出到屏幕上。
Learning notes | data Xiaobai uses dataease to make a large data screen
Laravel uses Tencent cloud cos5 full tutorial
Symmetric binary tree [tree traversal]
蚂蚁庄园安全头盔 7.8蚂蚁庄园答案
当前发布的SKU(销售规格)信息中包含疑似与宝贝无关的字
c语言面试写一个函数在字符串N中查找第一次出现子串M的位置。
C language interview to write a function to find the first occurrence of substring m in string n.
Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading
win系统下安装redis以及windows扩展方法
基于FPGA的VGA协议实现
PostgreSQL database timescaledb function time_ bucket_ Gapfill() error resolution and license replacement
3428. Put apples
Programmers' daily | daily anecdotes