美文网首页程序员C语言C++
小朋友学经典算法(12):分割字符串

小朋友学经典算法(12):分割字符串

作者: 海天一树X | 来源:发表于2018-06-14 17:55 被阅读93次

一、准备知识

在分割字符串之前,先来了解一些跟字符串相关的变量或函数:
(1)size_type:size_type由string类类型和vector类类型定义的类型,用以保存任意string对象或vector对象的长度,标准库类型将size_type定义为unsigned类型。

(2)string的find("x")函数,若找到则返回x的位置,没找到则返回npos。npos代表no postion,表示没找到,其值为-1

#include <iostream>
using namespace std;

int main()
{
    string s = "abcdefg";
    int x = s.find("abc");
    int y = s.find("ddd");
    cout << x << endl;
    cout << y << endl;
    
    return 0;
}

运行结果:

0
-1

(3)substr(x, y)

basic_string substr(size_type  _Off = 0,size_type _Count = npos) const;

参数
_Off:所需的子字符串的起始位置。默认值为0.
_Count:复制的字符数目。如果没有指定长度_Count或_Count+_Off超出了源字符串的长度,则子字符串将延续到源字符串的结尾。

返回值
一个子字符串,从其指定的位置开始

(4)C++字符串与C语言字符串之间的互相转化
C++中有string类型,C语言中没有string类型。若要把C++中的string类型转化为C语言中的string类型,必须用c_str()函数。

#include <iostream>
using namespace std;

int main()
{
    string s = "hello";
    const char *s1 = s.c_str();
    cout << s1 << endl;

    return 0;
}

反过来,若C语言中的字符串要转化为C++中的string类型,直接赋值即可

#include <iostream>
using namespace std;

int main()
{
    const char *a = "Hi";
    string s = a;
    cout << s << endl;

    return 0;
}

(5)atoi
atoi为C语言中的字符串转化为整型的函数。若要转化C++中的字符串,要先用c_str()转化为C语言的字符串,才能使用atoi。
atoi声明于<stdlib.h>或<cstdlib>中。

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

int main()
{
    string s = "23";
    int a = atoi(s.c_str());
    cout << a << endl;

    return 0;
}

反过来,有个整型转换为字符串的函数叫itoa,这个不是标准函数,有些编译器不支持。

二、split()实现

令人遗憾的是,C++标准库STL中没有提供分割字符串的函数,所以只能自己实现一个。

#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;

// 这里&是引用,不是取地址符
vector<string> split(const string &s, const string &separator)
{
    vector<string> v;
    
    string::size_type beginPos, sepPos;
    beginPos = 0;
    sepPos = s.find(separator);
    
    while(string::npos != sepPos)
    {
        v.push_back(s.substr(beginPos, sepPos - beginPos));
        beginPos = sepPos + separator.size();
        sepPos = s.find(separator, beginPos);
    }

    if(beginPos != s.length())
    {
        v.push_back(s.substr(beginPos));
    }

    return v;
}

int main()
{
    string s = "1 22 333";
    // 因为参数separator是string类型,所以这里只能用" ",不能用' '
    vector<string> vec = split(s, " ");
    vector<string>::iterator it;
    for(it = vec.begin(); it != vec.end(); it++)
    {
        // 输出字符串
        cout << (*it) << endl;
        // 输出整数
        cout << atoi((*it).c_str()) << endl;
    }
}

运行结果:

1
1
22
22
333
333

TopCoder & Codeforces & AtCoder交流QQ群:648202993
更多内容请关注微信公众号


wechat_public_header.jpg

相关文章

网友评论

    本文标题:小朋友学经典算法(12):分割字符串

    本文链接:https://www.haomeiwen.com/subject/qiayeftx.html