HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

String parsing/stripping code

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
codestrippingparsingstring

Problem

I am mostly interested in how the parse_string function could be improved. But any comments on my test strategy also welcome.

The input is a string which can be either all digits in which case the result should be the digits string OR there can be string formatting outside angle brackets which must be removed. the digit string is enclosed within the angle brackets in that case.

#include 
#include 

char* parse_string(const char* s, char* parsed) {
   /* sample string for angle brackets */
   const char* p = s;
   int lbrack = -1, rbrack = -1;
   while(*p) {
      if(*p == '') /* and last > char */
         rbrack = p - s;

      ++p;
   }

   /* strip everything BEFORE  if have brackets and in correct order */
   if(lbrack != -1 && rbrack != -1 && lbrack Sales Line 1", "123456", "", "", "", "", "", ">>>", "" };
   const char* output[] = { "737867", "123456", "", "123", "", "", ">>", "" };
   size_t sz = sizeof(input) / sizeof(input[0]);

   size_t i;
   for(i = 0; i  \"%s\", %s\n", input[i], output[i], strcmp(output[i], parse_string(input[i], buf)) == 0 ? "passed" : "failed");
   }
   return 0;
}

Solution

-
Add a buffer length parameter and then use strncpy to avoid overflow.

-
Your testing code hides the usage of the function. It's clearer to put it on a separate line:

for(i = 0; i  \"%s\", %s\n", 
                 input[i], output[i], strcmp(output[i], buf) == 0 ? "passed" : "failed");
}


  • You missed the out of order cases like `>123

Code Snippets

for(i = 0; i < sz; ++i) {
    parse_string(input[i], buf)
    printf("Test string \"%s\" => \"%s\", %s\n", 
                 input[i], output[i], strcmp(output[i], buf) == 0 ? "passed" : "failed");
}

Context

StackExchange Code Review Q#73940, answer score: 2

Revisions (0)

No revisions yet.