2016-11-19 27 views
-4

我需要一点点帮助解决这一问题,打破字符数组成字

你如何打破字符数组这样的“字符*文本”到基于特定的分隔符个别单词,并将它们保存形式“char * text []”,不使用strtok函数或除“iostream”之外的任何库。

在正常情况下,我会使用字符串而不是char数组和strtok函数,但在这种情况下,我根本不被允许。

感谢,

更新: 我已经包括了我试图

#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; 
} 
+0

如果没有这样做,在C++中获取某些东西有点困难。换句话说,例如,使用'strtok'。 – nbro

+0

我知道这很难,但你可以做一个[搜索](http://stackoverflow.com/questions/236129/split-a-string-in-c)。或者展示你的尝试。你来,只是说“做我的工作thx!”。 – Stargateur

+0

@Stargateur我明白你的批评,但我一直在寻找一段时间,几乎我发现的一切都需要使用字符串或矢量库。 –

回答

0

这里伪码

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使用类似的循环。我让你找到它。该算法的目的是将该行转换为多个单词。所以,只要你使用文字,行就必须活着。

+0

谢谢!什么是“nb_words”的类型? –

+0

@VictorL nb_words在这里**计数**的字数。而不是用于分配数组。所以他的类型与[new operator]的参数相同(http://www.cplusplus.com/reference/new/operator%20new/)。 – Stargateur