字符串操作笔记:输入三个字符串a,b,c,将a中b的第一次出现替为c

string str;
①pos = find(“str”)//函数,返回字符前面一个位置
②str.replace(pos,x,“aaa”)//函数,将str从pos位置开始,往后数四个字符,把他们替换称aaa
④find(char a,int pos)函数,在str字符串中,从pos开始,找到第一个a字符的位置
⑤substr(int pos_one,int pos_two),在str字符串中,把位置从pos_one到pos_two的字符截取下来

题目描述:输入三个字符串a,b,c,将a中b的第一次出现替为c

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

int main()
{
    string str[3];
    for(int i=0;i<3;i++)
    {
        cin>>str[i];
    }
    int pos =  str[0].find(str[1]);
    str[0].replace(pos,str[1].length(),str[2]);
    cout<<str[0];
    return 0;
}

字符串的使用:

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
bool judge(int n)
{
    if(0<=n&&n<=255)
        return true;
    else
        return false;
}

int main()
{
    string str;
    vector<int> v;
    getline(cin,str);
    int pos1 = 0;
    int pos;
    while(1)
    {
        pos = str.find('.',pos1);//find(char a,int pos)函数,在str字符串中,从pos开始,找到第一个a字符的位置
        string s = str.substr(pos1,pos);//substr(int pos_one,int pos_two),在str字符串中,把位置从pos_one到pos_two的符截取下来
        v.push_back(atoi(s.c_str()));
        pos1 = pos+1;
        if(v.size() == 4)
        break;
    }
    int flag = 1;
    for(int i=0;i<4;i++)
    {
        if(!judge(v[i]))
        {
            flag = 0;
        }
    }
    if(!flag)
        cout<<"no";
    else
        cout<<"yes";

    return 0;
}
发布了110 篇原创文章 · 获赞 14 · 访问量 6006

猜你喜欢

转载自blog.csdn.net/qq_38173631/article/details/104619654