Dividing char *array into words.

I need help with dividing char * array into words separated by "space".
I have char *arrayOfNums = "1 14 23 2 13" and I need to get:
arrayOfNums[0] = "1", arrayOfNums[1] = "14", arrayOfNums[2] = "23" etc.
I have seen solutions with <vector>string and string but I need exactly char array.

 
  
You can use strtok for that.
Beware, it is a tricky function.
http://en.cppreference.com/w/cpp/string/byte/strtok
Yes, beware of strtok which cannot be used with string literals (or pointers to string literals) of the type described in the OP without undefined behavior.

There is no way to do what you're describing as you've described it. If arrayOfNums is a pointer to char, there is no way to stuff another pointer to char in arrayOfNums[i].

Here's one possible way to achieve something similar to what you describe, although I would suggest using arrays to store the original data instead of pointing to a string literal and then using std::strtok to split 'em up as MiiNiPaa suggests rather than going this route:

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
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <cctype>

std::size_t count_tokens(const char* s)
{
    std::size_t token_count = 0;
    bool in_token = false;
    while (*s)
    {
        if (isspace(*s++))
            in_token = false;
        else if (!in_token)
        {
            in_token = true;
            ++token_count;
        }
    }

    return token_count;
}

const char** split(const char* s, const char** tokens)
{
    std::size_t token_count = 0;
    bool in_token = false;
    while (*s)
    {
        if (std::isspace(*s))
            in_token = false;
        else if ( !in_token )
        {
            in_token = true;
            tokens[token_count++] = s;
        }

        ++s;
    }

    tokens[token_count] = nullptr;
    return tokens;
}

const char** split(const char* s)
{
    return split(s, new const char*[count_tokens(s)+1]);
}

void out_token(const char* token)
{
    while (*token && !std::isspace(*token))
        std::cout << *token++ ;

    std::cout << '\n';
}

int main()
{
    const char* data = "1 14 23 2 13";

    const char** tokens = split(data);

    const char** cursor = tokens;
    while (*cursor)
        out_token(*cursor++);

    delete [] tokens;
}
thank you very much!
you've decided my problem!
Topic archived. No new replies allowed.