当前位置:网站首页>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
边栏推荐
- C language interview to write a function to find the first public string in two strings
- Apache ab 压力测试
- MySQL(十)
- How to find the literature of a foreign language journal?
- How to keep accounts of expenses in life
- How to solve sqlstate[hy000]: General error: 1364 field 'xxxxx' doesn't have a default value error
- You don't know the complete collection of recruitment slang of Internet companies
- Test the foundation of development, and teach you to prepare for a fully functional web platform environment
- JWT certification
- 字符串常量与字符串对象分配内存时的区别
猜你喜欢
Redis (II) - redis General Command
Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading
基于ADAU1452的DSP及DAC音频失真分析
Overview of FlexRay communication protocol
软件测试的几个关键步骤,你需要知道
FlexRay通信协议概述
You don't know the complete collection of recruitment slang of Internet companies
LM11丨重构K线构建择时交易策略
Tkinter window selects PCD file and displays point cloud (open3d)
拼多多败诉:“砍价免费拿”侵犯知情权但不构成欺诈,被判赔400元
随机推荐
力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)
屏幕程序用串口无法调试情况
"Parse" focalloss to solve the problem of data imbalance
牛客小白月赛52 E.分组求对数和(二分&容斥)
uniapp开发小程序如何使用微信云托管或云函数进行云开发
字符串常量与字符串对象分配内存时的区别
js装饰器@decorator学习笔记
[opencv] morphological filtering (2): open operation, morphological gradient, top hat, black hat
[Shell]常用shell命令及测试判断语句总结
dolphinscheduler3.x本地启动
How to keep accounts of expenses in life
JMeter function assistant - random value, random string, fixed value random extraction
软件测试到了35岁,真的就干不动了吗?
【从零开始】win10系统部署Yolov5详细过程(CPU,无GPU)
ST表预处理时的数组证明
[shell] summary of common shell commands and test judgment statements
JWT 认证
Redis (I) -- getting to know redis for the first time
拼多多败诉:“砍价免费拿”侵犯知情权但不构成欺诈,被判赔400元
C language sorting (to be updated)