c++ string 构造函数 赋值操作 字符串拼接

1.string构造函数

string(); //创建一个空的字符串,例如:string str;
string(const char* s); //使用字符串s初始化
string(const string& str);//使用一个string对象初始化另一个string对象
string(int n,char c); //使用n个字符c初始化

#include <iostream>
using namespace std;
#include <string>
void test01(){
    string s1;
    cout<<"str1= "<<s1<<endl;

    const char* str="hello world";
    string s2(str);
    cout<<"str2= "<<s2<<endl;

    string s3(s2);
    cout<<"str3= "<<s3<<endl;

    string s4(10,'a');
    cout<<"str4= "<<s4<<endl;
}
int main()
{
    test01();
    return 0;
}

2.string赋值操作(一般用operator= 这种方式)

给string字符串进行赋值
string& operator=(const chars); //char类型字符串 赋值给当前字符串
string& operator=(const string& s); //把字符串s赋给当前字符串
string& operator=(char c); //字符赋值给当前的字符串
string& assign(const char *s); //把字符串s赋值给当前的字符串
string& assign(const char *s,int n); //把字符串s的前n个字符赋给当前的字符串
string& assign(const string &s); //把字符串s赋给当前字符串
string& assign(int n,char c); //用n个字符c赋给当前的字符串

#include <iostream>
using namespace std;
#include <string>

void test01(){
    string s1="hello world";
    cout<<"str1= "<<s1<<endl;

    string s2=s1;
    cout<<"str2= "<<s2<<endl;

    string s3;
    s3='a';
    cout<<"str3= "<<s3<<endl;

    string s4;
    s4.assign("hello c++");
    cout<<"str4= "<<s4<<endl;

    string s5;
    s5.assign("hello c++",5);
    cout<<"str5= "<<s5<<endl;

    string s6;
    s6.assign(s5);
    cout<<"str6= "<<s6<<endl;

    string s7;
    s7.assign(10,'a');
    cout<<"str7= "<<s7<<endl;

}
int main()
{
    test01();
    return 0;
}

3.字符串拼接

实现在字符串末尾拼接字符串
string& operator+=(const char* str); //重载+=操作符
string& operator+=(const char c); //重载+=操作符
string& operator+=(const string& str); //重载+=操作符
string& append(const char *s); //把字符串s连接到当前字符串结尾
string& append(const char *s,int n); //把字符串s的前n个字符连接到当前字符串结尾
string& append(const string &s); //同operator+=(const string& str)
string& append(const string &s,int pos,int n);//字符串s从pos开始的n个字符连接到字符串结尾

#include <iostream>
using namespace std;
#include <string>

void test01(){
    string str1="我";
    str1+="爱学习";
    cout<<str1<<endl;

    str1 +=':';
    cout<<str1<<endl;

    string str2="c/c++";
    str1+=str2;
    cout<<str1<<endl;

    string s1="I";
    s1.append(" love ");
    cout<<s1<<endl;

    s1.append("study abc",6);
    cout<<s1<<endl;

    //s1.append(str2);
    //cout<<s1<<endl;

    s1.append(str2,2,3);
    cout<<s1<<endl;

}
int main()
{
    test01();
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值