string基本函数

例子:
#include<string> 
#include<iostream>
using namespace std;
int main(void)
{
    string str="abcdefghijklmn";
    string str1=str.substr(0,5);
    string str2=str.substr(2,5);
    cout << str1 << endl;
   cout << str2 << endl;
    
    return 0;
}


注意:
substr(pos,len)   函数返回从pos号位开始,长度为len的子串。
这里的pos是下标。(字符串的下标是从0开始的,不是从1开始)


例子:
#include<string>
#include<cstdio>
using namespace std;
int main(void)
{
    string str="abcd";
    printf("%s",str.c_str());
    return 0;
}
注意:
函数c_str()   将string类型转换成字符数组。
一般情况下,我们使用cout 输出一个string类型的变量。
在使用了c_str()函数之后,可以使用printf()函数进行输出。




例子:
操作符  +=
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main(void)
{
    string s1 = "123";
    string s2 = "456";
    s1+=s2;
    cout << s1; 
    return 0;
} 
  注意:+=是字符串的加法,可以将两个字符串拼接起来。

  

例子:
#include<iostream>
#include<string>
using namespace std;
int main(void)
{
    string str="abc",str2="def";
    str.insert(3,str2);
    cout << str << endl;
    return 0;    
} 
注意:

insert(pos,str)   ,在pos的位置开始插入字符串str

这里的pos是下标。



例子:
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int main(void)
{
    string str = "abcdefg";
    str.erase(3,2);
    cout << str << endl; //删除从下标3开始的2个字符 
    return 0;
} 
注意:

str.erase(pos,length),其中pos表示从下标pos开始删除,length是要删除的字符的个数。

  

 

 

转载于:https://www.cnblogs.com/zuimeiyujianni/p/9644018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值