简体   繁体   中英

Parsing a String in C, Without Strtok()

I need to parse a string in C by removing all non-alphabetic characters from it. To do this I am checking the ascii value of every char and making sure its within the correct bounds. 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.

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

** Edit 2

I solved the problem I was having with 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. 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". Data structure that represents that is what main() second argument is:

        // 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. As a such it might require a bit more than four weeks of C.

But we can be creative. There is "inbuilt in C" one non trivial data structure we might use. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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