Several ways of C++ string initialization

Method 1: The most simple and direct, direct assignment
string str1 = "test01" ;
Way 2:

string( size_type length, char ch );

  • A copy of ch with length as length (ie length ch)
string str2( 5, 'c' );  //  str2 'ccccc'
Method three:

string( const char *str );

string str3( "Now is the time..." );
Method four:

string( string &str, size_type index, size_type length );

  • A substring starting at index with a length of length, or starting with the elements from start to end.
string str4( str3, 11, 4 );  //将str3
Code example:
#include <iostream>
using namespace std;


int main() {
    
    
	string str1 = "test01" ;
	string str2( 5, 'c' );  //  str2 'ccccc'
	string str3( "Now is the time..." );
	string str4( str3, 11, 4 );

	cout << str1 << endl;
	cout << str2 << endl;
	cout << str3 << endl;
	cout << str4 << endl;
	
	return 0;
}

operation result:
insert image description here

See the official documentation for details: www.cppreference.com

Guess you like

Origin blog.csdn.net/VariatioZbw/article/details/116592225