C++字符串(String)

字符串的声明:

    string s;
    string str="abcdefg";
    char ch[]="abcdefg";
    //使用string类型初始化另一个string类型
    string s0(str);
    string s1(str,2);  //第2个字符开始复制cdefg
    string s2(str,2,3);  //从第二个字母开始复制连续3个字符cde
    cout<<s2<<endl;
    //使用char类型初始化另一个string类型
    string s3(ch);
    string s4(ch,3);  //开始复制前三个abc
    string s5(ch,2,3);  //从第二个字母开始复制连续3个字符cde
    cout<<s3<<endl; //abcdefg
    cout<<s4<<endl; //abc
    cout<<s5<<endl; //cde

 字符串的输入:

    cin>>s;     //不能有空格
    cout<<s<<endl;

    s=cin.get();  //每次输入一个字符
    cout<<s<<endl;

    getline(cin,s,'\n'); //每次输入一个字符串,以第三个参数作为结束符号
    cout<<s<<endl;

String的常用方法:

    //copy
    string s="abcde123";
    string s1=s;
    cout<<s1<<endl;
    //link
    string s2="Hello ";
    string s3="World";
    s2+=s3;
    cout<<s2<<endl;
    //compare
    string s4="abc";
    string s5="ea";
    int c=s4>s5;
    cout<<c<<endl;
    int d=s4<s5;
    cout<<d<<endl;
    int e=s4==s5;
    cout<<e<<endl;
    //flip #include<algorithm>
    string ss="Hello World!";
    reverse(ss.begin(),ss.end());
    cout<<ss<<endl;
    //find:return the index of the first find of the string "ll"
    string str="Hello ,yello";
    cout<<str.find("ll")<<endl;
    //replace
    string ch="thisismywork";
    ch.replace(1,2,"dd12");  //the substring(a,b) of String ch is replaced "dd12";
    cout<<ch<<endl;
    //append
    string s6="Hello ";
    s6.append("World");  //add a string "World" after the string s6;
    cout<<s6<<endl;
    //push_back
    string s7="Hello";
    s7.push_back('!');   //add a character after the string s7;
    cout<<s7<<endl;
    //insert
    string s8="HelloWorld";
    s8.insert(2,"PPP");
    cout<<s8<<endl;     //insert a string "PPP" into the index(2) of the string s8 ;
    //erase
    string s9="123456789";
    s9.erase(3,4);
    cout<<s9<<endl;   //delete the substring from the index(3) continuous 4 of the string s9;
    //swap
    string str1="Hello";
    string str2="world";
    str1.swap(str2);
    cout<<str1<<" "<<str2<<endl;  //swap the string str1 and the string str2
    //size();
    string str3="abcd e";
    cout<<str3.size()<<endl;    //the size of the string str3;
    //length();
    string str4="abcd e";
    cout<<str4.length()<<endl;    //the length of the string str4;

    cout<<str4.max_size()<<endl;    //return the max length of the string str4;

    s.clear();
    s.empty();

 

转载于:https://www.cnblogs.com/mypsq/p/4859035.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值