Victor L Victor L - 1 year ago 68
C Question

Breaking an array of chars into words

i need a little help with this problem,

How do you break a char array like this "char* text" into individual words based on specific delimiters and save them in the form "char* text[]" without using the strtok function or any libraries besides "iostream".

In a normal situation i would use strings instead of char arrays and the strtok function, but in this situation, i am simply not allowed to.

Thanks,

Update:
i have included what i have attempted

#include <iostream>
#include <fstream>
//#define MAX_CHARS_PER_LINE = 512;
//#define MAX_TOKENS_PER_LINE = 5;
using namespace std;
char stringToken(char* input_string);
int main(int argc, char* argv[])
{
char input_string[512];
ifstream infile;
infile.open(argv[1]);
while(!infile.eof())
{
infile.getline(input_string, 512);
cout << "Main line: " << input_string << endl;
stringToken(input_string);
}
infile.close();
return 0;
}
char stringToken(char* input_string)
{
//char* word;
//cout << "String token function: " << input_string << endl;
/*while(input_string >> word)
{
cout << word << endl;
}*/

char *tempone;
char *temptwo[5];

int ii=0,
jj=0;
while(input_string[ii] != '\0' && jj<5)
{
if((int)input_string[ii]!= 32 && (int)input_string[ii]!= 9 && (int)input_string[ii] != 44)
{
tempone[ii]=input_string[ii];
//cout << "\n\nindiv char" << input_string[ii] << "\t\t" << (int)input_string[ii] << "\n\n";
}
else
{
temptwo[jj]=tempone;
jj++;
//testing
cout << temptwo << endl;
}
ii++;

}



return 0;
}

Answer Source

Here a pseudo code

words split(line, delims)
{
    nb_words = cound_words(line);
    words = allocate_words(nb_words + 1); // words is a array of pointer
    i = 0
    j = 0
    while true
    {
        while line[i] in delims // we transform every delims into a end string
        {
            line[i] = end_string
            i++
        }
        if line[i] not end_string
        {
            words[j] = line + i // we stock the address of line[i]
            j++
            while line[i] not in delims and line[i] not end_string
            {
                i++
            }
        }
        else
        {
            words[j] = NULL // we end the array by NULL pointer
            return words
        }
    }
}

count_word use a similar loop. I let you find it. The purpose of this algorithm is to transform the line into multiple word. So line must life as long that you use words.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download