STL之string篇

  常用代码整理:

  

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
bool startWith(const string &str,const char* prex)
{
    int pos = str.find(prex);
    return pos == 0;
}
bool endWith(const string & str,char* prex)
{
    int pos = str.rfind(prex);
    return pos == str.length()-strlen(prex);
}

int main()
{
    char cstr[100] = "abcdefg";
    string str(cstr);

    //字节数
    //length与size内部实现与值都是一样的,length只是沿用
    //之前的c语言风格
    printf("%d %d
",str.length(),str.size());

    //追加
    string str2("12345");
    str += str2;            //方法1
    printf("%s
",str.c_str());
    char cstr2[100] = "12345";
    str.append(cstr2);         //方法2
    printf("%s
",str.c_str());

    //子串,substr参数(int pos,int len);
    str = str.substr(0,strlen(cstr));
    printf("%s
",str.c_str());

    //比较,返回值为int,为0相等
    int ret = str.compare(str2);
    printf("%d
",ret);

    //查找
    int pos = str.find("bcd",0);
    printf("pos = %d
",pos);

    //替代,替代的长度与字符串的长度可以不相等
    //对本身的修改
    str.replace(0,3,str2);
    printf("%s
",str.c_str());

    //插入
    //对本身的修改
    str.insert(2,str);
    printf("%s
",str.c_str());


    //请后缀判断
    cout<<"test
";
    string str5("123abcdg321");
    cout<<startWith(str5,"123")<<" "<<startWith(str5,"122")<<endl;
    cout<<endWith(str5,"321")<<" "<<endWith(str5,"322")<<endl;

    return 0;
}
View Code

例题有浙大PAT甲级1058

链接如下:

https://www.patest.cn/contests/pat-a-practise/1058

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string.h>
#include<cmath>
#include<algorithm>
using namespace std;

struct ST
{
    int a;
    int b;
    int c;
};

ST add(ST st1,ST st2)
{
    ST res;
    int add = 0;
    res.c = (st1.c+st2.c)%29;
    add =(st1.c+st2.c)/29;
    res.b = (st1.b+st2.b+add)%17;
    add = (st1.b+st2.b+add)/17;
    res.a = st1.a+st2.a+add;
    return res;
}
ST change(string str)
{
    ST st;
    int index1,index2;
    index1 = str.find('.');
    index2 = str.find('.',index1+1);
    string s1,s2,s3;
    s1 = str.substr(0,index1);
    s2 = str.substr(index1+1,index2-index1-1);
    s3 = str.substr(index2+1,str.length()-index2-1);
    //printf("index=%d,%d
",index1,index2);
    //printf("s1=%s,s2=%s,s3=%s
",s1.c_str(),s2.c_str(),s3.c_str());
    st.a = atoi(s1.c_str());
    st.b = atoi(s2.c_str());
    st.c = atoi(s3.c_str());
    return st;
}
int main()
{
    char cs1[20],cs2[20];
    scanf("%s%s",cs1,cs2);
    string str1(cs1),str2(cs2);
    ST res = add(change(str1),change(str2));
    printf("%d.%d.%d
",res.a,res.b,res.c);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/jlyg/p/7204302.html