将字符串分隔为分隔符strtok(C ++)

时间:2011-11-30 19:11:08

标签: c++

我有一个文字
我需要在每个提案中找到最大单词和最小单词。(以点分隔)
我写了一个函数来找到它。
我正在尝试将第一个单独的提案发送到函数

calculateString(token);

。 此变量标记被截断后。 谢谢你的回答!

更新:
问题:我需要在每个提案中找到最大和最小文本。在第一步它被截断。我怎么能避免它?(使用后不要截断) -

代码:

//Output/input /cin/cout
#include <iostream>
//System libary
#include <cstdlib>

//include printf/sprintf/scanf
#include <stdio.h>

//include string libary
#include <string>

//
#include <ctype.h>
#include <conio.h>

using namespace std;

void calculateString(char *str){
    char *temp;
    int len;
    int i = 0;
    char** stringArray;
    string long_word,short_word;

    temp = strtok(str," ,.!?");
    cout << "Str:" <<  str << "\n";
    int string_count = 0;//counting first word in string. 
    int string_count_short = 0;
      stringArray = new char*[string_count];
        while(temp = strtok(NULL," ,.!?"))
        {
                //cout << "\n" << temp << "\n";
                len = strlen(temp);
                if(len>string_count || string_count == 0){
                    string_count = len;
                    long_word =  temp;
                }
                if(len<string_count_short || string_count_short == 0){
                    string_count_short = len;
                    short_word=  temp; 

                }
        }       
       cout << "Longest word in all text is:" <<  long_word << "\n";
       cout << "Shortest word in all text is:" <<  short_word << "\n";
}
int main()
{
   char str[] = "Hello it's a test.Lets go.How are you?Andrej";
   char seps[]   = ".";

   char *token;
   token = strtok( str, seps );
   while( token != NULL )
   {
      /* While there are tokens in "string" */
      cout << " :: " << token << " ||\n";
      calculateString(token);

      /* Get next token: */
      token = strtok( NULL, seps );
   }
    //calculateString(str);

    system("pause");
    return 0;
}

3 个答案:

答案 0 :(得分:2)

您尝试以可重入的方式使用strtok(),这将无效,因为strtok()保持静态状态。 strtok()calculateString()之内的main()来自{{1}}中的来电中的状态。

您可能对strtok_r()感兴趣。或者更好的是,查看类似Boost.Tokenizer的内容。

答案 1 :(得分:1)

如果您的应用中的效果不是非常敏感,请尝试使用STL或Boost库,这将使您摆脱旧时尚问题。

希望它有所帮助。

答案 2 :(得分:1)

尝试这样的事情(这是黑客攻击)

/*Const string count */
   const int string_count = 10;
   /*Total string found */
   int str_count = 0;
   /* String delimiter*/
   char seps[]   = ".";

   char *token;
   token = strtok( str, seps );

   /* Creating array of chars */
   char** stringArray;
   /* Dynamic array of chars*/
   stringArray = new char*[string_count];

   while( token != NULL )
   {
      /* While there are tokens in "string" */
      stringArray[++str_count] = token; 
      /* Get next token: */
      token = strtok( NULL, seps );
   }
   /* Seperated propsal */
   for(int i=1;i <=str_count;i++){
         calculateString(stringArray[i]);
   }
相关问题