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是要删除的字符的个数。

  

 

猜你喜欢

转载自www.cnblogs.com/zuimeiyujianni/p/9644018.html
今日推荐