简体   繁体   English

在没有Strtok()的情况下在C中解析字符串

[英]Parsing a String in C, Without Strtok()

I need to parse a string in C by removing all non-alphabetic characters from it. 我需要通过从C中删除所有非字母字符来解析C中的字符串。 To do this I am checking the ascii value of every char and making sure its within the correct bounds. 为此,我要检查每个字符的ascii值,并确保其在正确的范围内。 It works just the way I want it to, so that's not the problem. 它只是按照我想要的方式工作,所以这不是问题。 What I am having trouble with, however, is storing the resulting strings after the parse is completed. 但是,我遇到的麻烦是在解析完成后存储结果字符串。 (I am 3 weeks into C by the way) Also if you notice that I used weird sizes for the arrays, that's because I purposely made them bigger than they needed to be. (顺便说一下,我进入C的时间为3周)另外,如果您注意到我对数组使用了奇怪的大小,那是因为我故意使它们变得比需要的大。

char * carry[2]; // This is to simulate argv
carry[1] = "hello1whats2up1"; // 0 is title so I placed at 1

char array[strlen(carry[1])]; // char array of string length
strcpy(array, carry[1]); // copied string to char array

char temp[strlen(carry[1]) + 1]; // Reusable char array
char * finalAnswer[10];

int m = 0, x = 0; // Indexes

if ((sizeof(carry))/8 > 1) { // We were given arguments

    printf("Array: %lu\n\n", sizeof(array));
    for (int i = 0; i < sizeof(array); i++)
    {
        if(isalpha(array[i])) { // A-Z & a-z
            //printf("%s\n", temp);
            temp[x] = array[i]; // Placing chars in temp array
            x++;

        }
        else {
            printf("String Length: %lu \nString Name: %s \nWord Index: %d \n\n",
                   strlen(temp), temp, m); // Testing Purposes
            strcpy(finalAnswer[m], temp); // Copies temp into the final answer *** Source of Error

            for(int w = 0; w < sizeof(temp); w++) { temp[w] = '\0'; } // Clears temp

            x = 0;
            m++;
        }
    }
    printf("String Length: %lu \nString Name: %s \nWord Index: %d \n",
           strlen(temp), temp, m); // Testing Purposes
    strcpy(finalAnswer[m], temp);

    for(int w = 0; w < sizeof(temp); w++) { temp[w] = '\0'; } // Clears temp

    x = 0;
}

else { printf("No Arguments Given\n"); }

printf("\n");

** Edit **编辑

The error I keep getting is when I try copying temp to finalAnswer 我一直遇到的错误是当我尝试将temp复制到finalAnswer时

** Edit 2 **编辑2

I solved the problem I was having with char * finalAnswer[10] 我解决了char * finalAnswer [10]遇到的问题

When I was trying to use strcpy on finalAnswer, I never specified the size that was needed to store the particular string. 当我尝试在finalAnswer上使用strcpy时,我从未指定存储特定字符串所需的大小。 Works fine after I did it. 我做完后效果很好。

Since you have solved the actual string parsing, your last comment, I shall take as the actual requirement. 由于您已经解决了实际的字符串解析问题,因此您的最后评论是我的实际要求。

"... I want to create a list of words with varying length that can be accessed by index ..." “ ...我想创建一个长度可变的单词列表,可以通过索引访问...”

That is certainly not a task to be solved easily if one is "three weeks into C". 如果一个人“进入C的三周”,那当然不是容易解决的任务。 Data structure that represents that is what main() second argument is: 表示那是main()第二个参数的数据结构是:

        // array (of unknown size)
        // of pointers to char
        char * argv[] ;

This can be written as an pointer to pointer: 可以将其写为指向指针的指针:

        // same data structure as char * []
        char ** list_of_words ;

And this is pushing you straight into the deep waters of C. An non trivial C data structure. 这将您直接带入C的深水。非平凡的C数据结构。 As a such it might require a bit more than four weeks of C. 因此,可能需要超过4周的C时间。

But we can be creative. 但是我们可以发挥创造力。 There is "inbuilt in C" one non trivial data structure we might use. 我们可以使用“内置于C中”一种非平凡的数据结构。 A file. 一份文件。

We can write the words into the file. 我们可以将单词写到文件中。 One word one line. 一字一线。 And that is our output: list of words, separated by new line character, stored in a file. 这就是我们的输出:存储在文件中的单词列表,用换行符分隔。

We can even imagine and write a function that will read the word from that result "by index". 我们甚至可以想象并编写一个函数,该函数将从结果中“按索引”读取单词。 As you (it seems) need. 如您(看来)的需要。

         // hint: there is a FILE * behind
         int words_count = result_size () ;
         const char * word = result_get_word(3) ;

Now, I have boldly gone ahead and have written "all" of it, beside that last "crucial" part. 现在,我大胆地前进,并在最后一个“关键”部分旁边写下了“全部”内容。 After all, I am sure you would like to contribute too. 毕竟,我相信您也愿意做出贡献。

So the working code (minus the result_size) and result_get_word() ) is alive and kicking here: https://wandbox.org/permlink/uLpAplNl6A3fgVGw 因此,工作代码(减去result_size)和result_get_word()仍然有效,并在此处运行: https : //wandbox.org/permlink/uLpAplNl6A3fgVGw

To avoid the "Wrath of Khan" I have also pasted it here: 为了避免“可汗之怒”,我也将其粘贴在这里:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/*
 task: remove all non alpha chars from a given string, store the result
 */

 int process_and_save (FILE *, const char *) ;
 int dump_result(FILE *) ;

 int main( const int argc, const char * argv[] )
 {
   const char * filename = "words.txt";
   const char * to_parse = "0abra123ka456dabra789" ;

    (void)(&argc) ; (void)argv ; // pacify the compiler warnings 

     printf("\nInput: %s", to_parse ) ;
     int retval = process_and_save(fopen(filename, "w"), to_parse ) ;
     if ( EXIT_FAILURE != retval )
      {
    printf("\n\nOutput:\n") ;
    retval = dump_result(fopen(filename, "r"));
      }
    return retval ;
  }

  int process_and_save (FILE * fp, const char * input )
  {
    if(!fp) {
       perror("File opening failed");
         return EXIT_FAILURE;
     }
    // 
    char * walker = (char *)(input) ;
    while ( walker++ ) 
    {
         if ( ! *walker ) break ;
         if ( isalpha(*walker) ) {
            fprintf( fp, "%c", *walker ) ;
            // I am alpha but next one is not
            // so write word end, next
             if ( ! isalpha(*(walker +1) ) )
                   fprintf( fp, "\n" ) ;
          }
    }
    fclose(fp);
    return EXIT_SUCCESS; 
 }

 int dump_result(FILE* fp )
 {
  if(!fp) {
    perror("\nFile opening failed");
      return EXIT_FAILURE;
  }

   int c; while ((c = fgetc(fp)) != EOF) { putchar(c); }

   if (ferror(fp))
       puts("\nI/O error when reading");

       fclose(fp);
          return EXIT_SUCCESS;
  }

I think this is functional and does the job of parsing and storing the result. 我认为这是功能性的,并且可以解析和存储结果。 Not in the complex data structure but in the simple file. 不是在复杂的数据结构中,而是在简单的文件中。 The rest should be easy. 其余的应该很容易。 If need help please do let me know. 如果需要帮助,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM