как разделить строковое значение, содержащее символы и цифры - PullRequest
0 голосов
/ 17 мая 2011

У меня есть std::string s=n8Name4Surname. Как я могу получить в 2 строки имя и фамилию? THX

Ответы [ 5 ]

3 голосов
/ 17 мая 2011

Один из способов сделать это - использовать 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> > 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;
    }
}

РЕДАКТИРОВАТЬ

Если вы поместите результаты в vector, его код будет еще меньше:

#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));
    }

}
2 голосов
/ 17 мая 2011

Вы можете обнаружить числовые символы в строке, используя функцию isdigit(mystring.at(position), а затем извлечь подстроку между этими позициями.

См .:

http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

1 голос
/ 17 мая 2011

Простой подход STL:

#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string s= "n8Name4Surname";

    std::vector<std::string> parts;

    const char digits[] = "0123456789";

    std::string::size_type from=0, to=std::string::npos;

    do
    {
        from = s.find_first_of(digits, from);
        if (std::string::npos != from)
            from = s.find_first_not_of(digits, from);

        if (std::string::npos != from)
        {
            to = s.find_first_of(digits, from);
            if (std::string::npos == to)
                parts.push_back(s.substr(from));
            else
                parts.push_back(s.substr(from, to-from));

            from = to; // could be npos
        } 

    } while (std::string::npos != from);

    for (int i=0; i<parts.size(); i++)
       std::cout << i << ":\t" << parts[i] << std::endl;


    return 0;
}
1 голос
/ 17 мая 2011

Используйте Boost tokenizer с цифрами 0-9 в качестве разделителей. Затем выбросьте строку, содержащую «n». Это излишне, я понимаю ...

0 голосов
/ 17 мая 2011

Образец обязательного повышения духа:

#include <string>
#include <boost/spirit/include/qi.hpp>
#include <iostream>

int main()
{
    std::string s= "n8Name4Surname";

    std::string::const_iterator b(s.begin()), e(s.end());
    std::string ignore, name, surname;

    using namespace boost::spirit::qi;
    rule<std::string::const_iterator, space_type, char()> 
        digit = char_("0123456789"),
        other = (char_ - digit);

    if (phrase_parse(b, e, *other >> +digit >> +other >> +digit >> +other, space, ignore, ignore, name, ignore, surname))
    {
        std::cout << "name = " << name << std::endl;
        std::cout << "surname = " << surname << std::endl;
    }

    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...