spliting string and token as string

is there any way to split a string and get token as string?
strtok returns char* ..
Last edited on
You can construct a string from the return value of strtok(). When a delimiter is found it is replaced by a null char.
Use boost split
http://www.boost.org/doc/libs/1_54_0/doc/html/string_algo/reference.html#header.boost.algorithm.string.split_hpp

Or something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <iterator>

template < typename OUTPUT_ITERATOR >
OUTPUT_ITERATOR split( const std::string& str, const std::string& delimiters,
                       OUTPUT_ITERATOR dest )
{
    std::string::size_type pos = str.find_first_of(delimiters) ;
    std::string::size_type start = 0 ;

    while( pos != std::string::npos )
    {
        std::string token = str.substr( start, pos-start ) ;
        if( !token.empty() ) *dest++ = token ;
        start = pos+1 ;
        pos = str.find_first_of( delimiters, start ) ;
    }

    if( start < str.size() ) *dest++ = str.substr(start) ;

    return dest ;
}

std::vector<std::string> split( const std::string& str, const std::string& delimiters )
{
    std::vector<std::string> result ;
    split( str, delimiters, std::back_inserter(result) ) ;
    return result ;
}

int main()
{
    const std::string jabber = "`Twas brillig, and the slithy toves\n"
                                 "Did gyre and gimble in the wabe:\n"
                                 "All mimsy were the borogoves,\n"
                                 "And the mome raths outgrabe.\n" ;
    const std::string delimiters = "\n ,:.!" ;

    int n = 0 ;
    for( const std::string& token : split( jabber, delimiters ) )
        std::cout << ++n << ". " << token << '\n' ;
    std::cout << '\n' ;

    split( jabber, delimiters, std::ostream_iterator<std::string>( std::cout, " | " ) ) ;
    std::cout << "\n\n" ;

    const char cstr[] = "Beware the Jabberwock, my son!\n"
                         "The jaws that bite, the claws that catch!\n"
                         "Beware the Jubjub bird, and shun\n"
                         "The frumious Bandersnatch!\n" ;

    split( cstr, delimiters, std::ostream_iterator<std::string>( std::cout, " | " ) ) ;
    std::cout << '\n' ;

}

http://ideone.com/c6C0Dd
Last edited on
Topic archived. No new replies allowed.