• c++ 字符串函数用法举例


    • 1. substr()
    • 2. replace()
    • 例子:split()

    字符串切割: substr

    函数原型:

    string substr ( size_t pos = 0, size_t n = npos ) const;

    解释:抽取字符串中从pos(默认为0)开始,长度为npos的子字串

    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
        string  s = "hello";
       cout << s.substr() << endl; cout
    << s.substr(2) << endl; cout << s.substr(2, 2) << endl;
    cout << s.substr(2, string::npos) << endl; }

    结果

    hello
    llo ll
    llo

     注意:string 类将 npos 定义为保证大于任何有效下标的值

    字符串替换:replace

    函数原型:

    basic string& replace(size_ type Pos1, size_type Num1, const type* Ptr ); 
    basic string& replace(size_ type Pos1, size_type Num1,const string Str );
    

    替换用Ptr(或str)替换字符串从Pos1开始的Num1个位置

    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
        string  s = "hello";
        string m = s.replace(1, 2, "mmmmm");
        cout << m << endl;
    }

    结果:hmmmmmlo

    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
        string  s = "hello";
        char a[] = "12345";
        string m = s.replace(1, 2, a);
        cout << m << endl;
    }

    结果:h12345lo

    举例

    split()函数

    #include <iostream>
    #include <vector>
    using namespace std;
    
    vector<string> split(const string &s, const string &delim)
    {
        vector<string> elems;
        size_t pos = 0;
        size_t len = s.length();
        size_t delim_len = delim.length();
        if (delim_len == 0)
        {
            elems.push_back(s.substr(0, len));
            return elems;
        }
        while (pos < len)
        {
            int find_pos = s.find(delim, pos);
            if (find_pos < 0)
            {
                elems.push_back(s.substr(pos, len-pos));
                break;
            }
            elems.push_back(s.substr(pos, find_pos-pos));
            pos = find_pos + delim_len;
        }
        return elems;
    }
    
    int main()
    {
        vector<string> vec = split("hello^nihao^ohyi", "^");
        for (int i = 0; i < vec.size(); ++i)
            cout << vec[i] << endl;
    }
  • 相关阅读:
    mybatis的mapper特殊字符转移以及动态SQL条件查询
    MySQL查询结果集字符串操作之多行合并与单行分割
    MySQL查询之内连接,外连接查询场景的区别与不同
    SpringBoot异步使用@Async原理及线程池配置
    SpringBoot 属性配置文件数据注入配置和yml与properties区别
    MySQL实战45讲第33讲
    Beta冲刺第1次
    Beta冲刺第5次
    Beta冲刺第4次
    Beta冲刺第3次
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3891621.html
Copyright © 2020-2023  润新知