繁体   English   中英

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

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

我需要通过从C中删除所有非字母字符来解析C中的字符串。 为此,我要检查每个字符的ascii值,并确保其在正确的范围内。 它只是按照我想要的方式工作,所以这不是问题。 但是,我遇到的麻烦是在解析完成后存储结果字符串。 (顺便说一下,我进入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");

**编辑

我一直遇到的错误是当我尝试将temp复制到finalAnswer时

**编辑2

我解决了char * finalAnswer [10]遇到的问题

当我尝试在finalAnswer上使用strcpy时,我从未指定存储特定字符串所需的大小。 我做完后效果很好。

由于您已经解决了实际的字符串解析问题,因此您的最后评论是我的实际要求。

“ ...我想创建一个长度可变的单词列表,可以通过索引访问...”

如果一个人“进入C的三周”,那当然不是容易解决的任务。 表示那是main()第二个参数的数据结构是:

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

可以将其写为指向指针的指针:

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

这将您直接带入C的深水。非平凡的C数据结构。 因此,可能需要超过4周的C时间。

但是我们可以发挥创造力。 我们可以使用“内置于C中”一种非平凡的数据结构。 一份文件。

我们可以将单词写到文件中。 一字一线。 这就是我们的输出:存储在文件中的单词列表,用换行符分隔。

我们甚至可以想象并编写一个函数,该函数将从结果中“按索引”读取单词。 如您(看来)的需要。

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

现在,我大胆地前进,并在最后一个“关键”部分旁边写下了“全部”内容。 毕竟,我相信您也愿意做出贡献。

因此,工作代码(减去result_size)和result_get_word()仍然有效,并在此处运行: https : //wandbox.org/permlink/uLpAplNl6A3fgVGw

为了避免“可汗之怒”,我也将其粘贴在这里:

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

我认为这是功能性的,并且可以解析和存储结果。 不是在复杂的数据结构中,而是在简单的文件中。 其余的应该很容易。 如果需要帮助,请告诉我。

暂无
暂无

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

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