C++基础-string类型-构造函数

  • 构造函数
string();	// 默认创建一个空字符串
string( size_type length, char ch );// 创建length个字符ch的字符串
string( const char *str );//创建str的一个副本字符串
string( const char *str, size_type index);//截取str索引index开始到末尾创建一个新字符串
string( string &str, size_type index, size_type length );// 截取str索引index开始长度为length创建新字符串
string( input_iterator start, input_iterator end );	// 还不会,后期再补,高手请指教,谢谢
  • 举例
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

int main(void)
{
        string str1;    // 创建一个空串
        cout << "str1: " << "这是一个空串!" << str1 << endl;
        str1 = "This is a string";
        cout << "str1: " << str1 << endl;

        string str2(5, 'H');
        cout << "str2: " << str2 << endl;

        string str3(str1);
        string str4(str1, 3);
        cout << "str3: " << str3 << endl;
        cout << "str4: " << str4 << endl;

        string str5(str1, 5, 8);
        cout << "str5: " << str5 << endl;
        return 0;
}
[[PC:~/WorkSpace/CPP/string/3.2.3$ ./constructors.exe 
str1: 这是一个空串!
str1: This is a string
str2: HHHHH
str3: This is a string
str4: s is a string
str5: is a str
lexy@LexyPC:~/WorkSpace/CPP/string/3.2.3$ #include <iostream>
lexy@LexyPC:~/WorkSpace/CPP/string/3.2.3$ #include <string>
lexy@LexyPC:~/WorkSpace/CPP/string/3.2.3$ 
lexy@LexyPC:~/WorkSpace/CPP/string/3.2.3$ using std::cout;
using std::endl;
using std::string;

猜你喜欢

转载自blog.csdn.net/ShiJian_ShaLou/article/details/84783662