string 用法

版权声明:转载时 别忘了注明出处 https://blog.csdn.net/ZCY19990813/article/details/81559379

最开始接触string是因为它可以很方便的查找是不是字串  下面一一讲解

1.定义:

string s;   
cin>>s; 

或者

string s="abcdef";

2.基本用法

   长度 

s.size();    

   把s2复制到s1中

strcpy(s1,s2);  

   连接2个字符串

s1=s1+s2;

   比较字符串  直接用关系运算符  ==   >   <   !=  >=   <=

   获取第一个字符  

string:const_iterator it=s.begin();   
count<<*it<<endl;

   获取最后一个字符

string:const_iterator it=s.end();  
it--; 
count<<*it<<endl;

倒置串

reserve(s.begin(),s.end());

查找串(判断s1是不是s的字串)

s.find(s1);

截取字符串

s.substr(a,n);//在s的a位置截取长度为n的字符串

3.下面重点讲一下find函数

它可以判断是不是字串  也就是说一个串有没有在另一个串中出现过

find这个函数找到返回字串的起始位置  找不到返回-1

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <deque>
#include <map>
using namespace std;
const int MAX=1e5+10;
typedef long long ll;
int a[MAX];
int main()
{
    string s1,s2;
    cin>>s1>>s2;
    if(s1.find(s2)==-1)
        printf("no\n");
    else
        printf("yes\n");
    return 0;
}

有一个问题find可不可以判断出现过几次呢   正常来说  是没有办法的  但有一个小技巧  可以找完一个将字符串改一下在判断  看代码

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <deque>
#include <map>
using namespace std;
const int MAX=1e5+10;
typedef long long ll;
int a[MAX];
int main()
{
    string s,t;
    int ans=0;
    cin>>s>>t;
    while(1)
    {
        int tt=s.find(t);
        if(tt!=-1)
        {
            s[tt]='1';
            ans++;
        }
        else
            break;
    }
    printf("%d",ans);
    return 0;
}

请看    https://blog.csdn.net/ZCY19990813/article/details/81394713  的第一题

请看 https://blog.csdn.net/ZCY19990813/article/details/81542308  的第三题

这篇博客是按自己理解写的   如有问题 欢迎指出

猜你喜欢

转载自blog.csdn.net/ZCY19990813/article/details/81559379
今日推荐