如何拆分包含字符和数字的字符串值 [英] how to split a string value that contains characters and numbers

查看:179
本文介绍了如何拆分包含字符和数字的字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: string s = n8Name4Surname 。如何在2个字符串中获取姓名和姓氏? THX

解决方案

一种方法是使用 Boost.Tokenizer 。请参阅此示例:

  #include< string& 
#include< boost / tokenizer.hpp>
#include< boost / foreach.hpp>
int main()
{
using namespace std;
using namespace boost;
string text =n8Name4Surname。;

char_separator< char> sep(0123456789);
tokenizer< char_separator< char> >令牌(text,sep);

string name,surname;
int count = 0;
BOOST_FOREACH(const string& s,tokens)
{
if(count == 1)
{
name = s;
}
if(count == 2)
{
surname = s;
}
++ count;
}
}

EDIT >

如果将结果放在向量中,它的代码更少:

  #include< string> 
#include< boost / tokenizer.hpp>
#include< boost / foreach.hpp>
#include< algorithm>
#include< iterator>
#include< vector>

int main()
{
using namespace std;
using namespace boost;
string text =n8Name4Surname。;

char_separator< char> sep(0123456789);
tokenizer< char_separator< char> >令牌(text,sep);

vector< string>名称;
tokenizer< char_separator< char> > :: iterator iter = tokens.begin();
++ iter;
if(iter!= tokens.end())
{
copy(iter,tokens.end(),back_inserter
}

}


I have a std::string s=n8Name4Surname. How can I obtain in 2 strings the Name and the Surname? THX

解决方案

One way to do this is using Boost.Tokenizer. See this example:

#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
int main()
{
    using namespace std;
    using namespace boost;
    string text="n8Name4Surname.";

    char_separator<char> sep("0123456789");
    tokenizer<char_separator<char> > tokens(text, sep);

    string name, surname;
    int count = 0;
    BOOST_FOREACH(const string& s, tokens)
    {
        if(count == 1)
        {
            name = s;
        }
        if(count == 2)
        {
            surname = s;
        }
        ++count;
    }
}

EDIT

If you put the results in a vector, its even less code:

#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <algorithm>
#include <iterator>
#include <vector>

int main()
{
    using namespace std;
    using namespace boost;
    string text="n8Name4Surname.";

    char_separator<char> sep("0123456789");
    tokenizer<char_separator<char> > tokens(text, sep);

    vector<string> names;
    tokenizer<char_separator<char> >::iterator iter = tokens.begin();
    ++iter;
    if(iter != tokens.end())
    {
        copy(iter, tokens.end(), back_inserter(names));
    }

}

这篇关于如何拆分包含字符和数字的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆