Introduction to the C++ String Class

Old Zhou has a code chat, where the flowers fall under the keyboard; each line weaves a dream of the galaxy,poetry and code nurture a clear virtue.

I am Old Zhou! Follow the “Old Zhou Code Chat” public account for more selected content!~ ∞ ~ ∞ Introduction to string ∞ ~∞ ~

string is a class in the C++ standard library that handles strings, providing a rich set of functionalities to manipulate strings. This statement may seem vague, but don’t worry, Old Zhou will focus on commonly used aspects in projects…

~ ∞ ~ ∞ Declaration and Initialization of string∞ ~∞ ~

// String.cpp

#include <iostream>

using namespace std;

void initString(){

// Common initializations

string s1;

string s2(“laoz V5”);

string s3 = “laozV5”;

string s4 = s3;

string s5(s4);

cout<<“s1:”<<s1<<endl;

cout<<“s2:”<<s2<<endl;

cout<<“s3:”<<s3<<endl;

cout<<“s4:”<<s4<<endl;

cout<<“s5:”<<s5<<endl;

// Less common initializations

string s6(6, ‘z’);

string s7(s3, 1,4); # Starting from the 0th byte, count the next 4 bytes

cout<<“s6:”<<s6<<endl;

cout<<“s7:”<<s7<<endl;

}

int main(){

initString();

return 0;

}

Execution Result:# g++ String.cpp -o String# ./String

s1:

s2:laozV5

s3:laozV5

s4:laozV5

s5:laozV5

s6:zzzzzz

s7:aozV # The first 4 bytes starting from the first byte of s3

~ ∞ ~ ∞ String Add, Delete, Search, and Modify∞ ~∞ ~

//String.cpp

#include <iostream>

using namespace std;

void operatorString(){

// Add

cout<<“String add:”<<endl;

string s1 = “hello world!”, s2 = “la”;

string s3 = s1+” “+s2; // The “+” operator is supported

cout<<” s1:”<<s1<<” s2:”<<s2<<” s3:”<<s3<<endl;

s3 += ” handsome!”; // The “+=” operator is supported

cout<<” s3+=:”<<s3<<endl;

s3.insert(8, “oz”); // Insert “oz” at the 8th byte position, shifting the following bytes

cout<<” s3.insert():”<<s3<<endl;

s3.push_back(‘n’); // Add ‘n’ character to the end of the string, string addition is not supported

cout<<” s3 push_back():”<<s3<<endl;

// Delete

cout<<“\nString remove:”<<endl;

s3.erase(0, 5); // Delete the first 5 bytes from position 0

cout<<” s3.erase():”<<s3<<endl;

s3.pop_back(); // Delete the last byte

cout<<” s3.pop_back():”<<s3<<endl;

s3.clear(); // Clear the string

cout<<” s3.clear():”<<s3<<endl;

// Query

cout<<“\nString query:”<<endl;

cout<<” s3.empty():”<<s3.empty()<<endl; // Check if the string is empty

s3 = s1;

cout<<” s3.size():”<<s3.size()<<endl; // C++11, string length

cout<<” s3.length():”<<s3.length()<<endl; // Same as size()

// Old Zhou’s compiler defaults to allocate 30, can use s3.reserve to allocate

cout<<” s3.capacity():”<<s3.capacity()<<endl;

cout<<” s3[0]:”<<s3[0]<<endl; // Supports collection-style access

cout<<” s3.at(0):”<<s3.at(0)<<endl; // Get the byte at the specified position

cout<<” s3.front():”<<s3.front()<<endl; // Get the first byte

cout<<” s3.back():”<<s3.back()<<endl; // Get the last byte

cout<<” s3:”<<s3<<endl;

// Get 3 bytes starting from the 3rd position

cout<<” s3.substr():”<<s3.substr(3,3)<<endl;

// Find the position of the specified string from the left

cout<<” s3.find():”<<s3.find(“wo”)<<endl;

// Find the position of the specified string from the right (returns the position counted from the left)

cout<<” s3.rfind():”<<s3.rfind(“wo”)<<endl;

// Modify

cout<<“\nString modify:”<<endl;

s3.replace(2,4, “good”); // Replace 4 bytes starting from the 2nd byte

cout<<” s3.replace():”<<s3<<endl;

}

int main(){

operatorString();

return 0;

}

Execution Result:# g++ String.cpp -o String# ./String

String add:

s1:hello world! s2:la s3:hello world! la

s3+=:hello world! la handsome!

s3.insert():hello woozrld! la handsome!

s3 push_back():hello woozrld! la handsome!n

String remove:

s3.erase(): woozrld! la handsome!n

s3.pop_back(): woozrld! la handsome!

s3.clear():

String query:

s3.empty():1

s3.size():12

s3.length():12

s3.capacity():30

s3[0]:h

s3.at(0):h

s3.front():h

s3.back():!

s3:hello world!

s3.substr():lo

s3.find():6

s3.rfind():6

String modify:

s3.replace():hegoodworld!

~ ∞ ~ ∞ String Conversion between string and Numeric Values∞ ~∞ ~

// String.cpp

#include <iostream>

using namespace std;

void conversionString(){

// Conversion between numbers and string

int i = stoi(“66”);

double j = stod(“88.88”);

cout<<“stoi():”<<i<<” stod():”<<j<<endl;

string s1 = to_string(66);

string s2 = to_string(88.88);

cout<<“to_string(int):\””

<<s1<<“\” to_string(double):\””+s2<<“\””<<endl;

// Conversion between string and char string

const char* cstr = s1.c_str();

const char* data = s1.data();

cout<<“s.c_str():\””<<cstr<<“”s.data():\””

<<data<<“\””<<endl;

string s3(cstr);

cout<<“s3:(cstr):\””<<s3<<“\””<<endl;

}

int main(){

conversionString();

return 0;

}

Execution Result:# g++ String.cpp -o String# ./String

stoi():66 stod():88.88

to_string(int):”66″ to_string(double):”88.880000″

s.c_str():”66″ s.data():”66″

s3:(cstr):”66″

~ ∞ ~ ∞ String Splitting∞ ~∞ ~

// String.cpp

#include <iostream>

#include <sstream>

using namespace std;

void splitString(){

// Split string

string input = “laoz&laom&laol&laof”;

istringstream ss(input);

string token;

while(getline(ss, token, ‘&’)){

cout<<token<<endl;

}

// Merge strings

ostringstream oss;

oss << “my name is “<<“laoz”<<18;

string s3 = oss.str();

cout<<“s3:”<<s3<<endl;

}

int main(){

splitString();

return 0;

}

Execution Result:# g++ String.cpp -o String# ./String

laoz

laom

laol

laof

s3:my name is laoz18

~ ∞ ~ ∞ Trimming Spaces from Both Ends of String∞ ~∞ ~

// String.cpp

#include <iostream>

#include <algorithm>

using namespace std;

void ltrim(string& s){ // Remove left spaces

s.erase(s.begin(),

find_if(s.begin(), s.end(),

[](unsigned char ch){

return !isspace(ch);

}

)

);

}

void rtrim(string& s){ // Remove right spaces

auto it = find_if(s.rbegin(), s.rend(),

[](unsigned char ch){

return !isspace(ch);

});

s.erase(it.base(), s.end());

}

void trim(string& s){ // Remove spaces from both ends

ltrim(s);

rtrim(s);

}

int main(){

string s=” laoz hello “;

ltrim(s); // Remove left spaces

cout<<“s:”<<s[0]<<” s.len:”<<s.length()<<endl;

cout<<“s:”<<s<<endl;

rtrim(s); // Remove right spaces

cout<<“s:”<<s[0]<<” s.len:”<<s.length()<<endl;

string s1 = ” laoma hello “;

trim(s1); // Remove spaces from both ends

cout<<“s:”<<s[0]<<” s.len:”<<s.length()<<endl;

return 0;

}

Execution Result:# g++ String.cpp -o String# ./String

s:l s.len:13 # Result after removing left spaces

s:laoz hello

s:l s.len:10 # Result after removing right spaces

s:l s.len:10 # Result after removing spaces from both ends

~ ∞ ~ ∞ String Comparison∞ ~∞ ~

// String.cpp

#include <iostream>

using namespace std;

void upperLowerCompare(){

string s = “Hello World”;

transform(s.begin(), s.end(), s.begin(), ::toupper); // Convert to uppercase

cout<<“s upper:”<<s<<endl;

transform(s.begin(), s.end(), s.begin(), ::tolower); // Convert to lowercase

cout<<“s lower:”<<s<<endl;

string s1 = “Laoz”;

string s2 = “LAOz”;

if(s1.compare(s2) == 0){ // Precise comparison of two strings (including case)

cout<<“compare ok!”<<endl;

}else{

transform(s1.begin(), s1.end(), s1.begin(), ::toupper);

transform(s2.begin(), s2.end(), s2.begin(), ::toupper);

if (s1.compare(s2) == 0){

cout<<“compare ok ignore case”<<endl;

}else{

cout<<“compare failed”<<endl;

}

}

}

int main(){

upperLowerCompare();

return 0;

}

Execution Result:# g++ String.cpp -o String# ./String

s upper:HELLO WORLD

s lower:hello world

compare ok ignore case

Old Zhou: “The foundation is not solid, the earth shakes! Just like in a game, you can’t skip the novice village; you can’t expect to unleash a big move without even knowing how to do a basic attack, right? Skills can be forgotten more cleanly than a first love, but you must chew through the basics like an old workhorse—after all, if the system crashes one day, at least we should be able to manually code a fake Hello World, right?”

Leave a Comment