Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

strextract fails if search start is the same as the input string #49

Open
mdbartos opened this issue Jul 30, 2017 · 1 comment
Open

Comments

@mdbartos
Copy link
Member

The current code for strextract assumes the search start is shorter than the length of the input string.

If we want to extract a substring starting at the beginning of a string, we might want to use the input string as the search start string. However, this doesn't work for the current implementation due to:

        begin += strlen(search_start);

I can see reasons for both implementations; maybe we could include an argument that specifies the desired behavior.

@imondrag
Copy link
Contributor

imondrag commented Jul 31, 2017

That's the defined behavior for strextract.

"Searches for the left-most c string in between search_start and search_end ..."

We shouldn't need to modify the existing implementation, you can use temporary buffers and strcat for the described behavior.

However, I would suggest the use of some pointer arithmetic to achieve your desired behavior:

char unparsed_string[] = "10:54pm Code 09 This is a test message\r";

// The string we want to search and keep.. with extra room for the parsed result
char parsed_error_code[ sizeof("Code ##") ] = "Code ";

// strextract returns the address of search_end on success,
// let's store the address of the space after the error code number
char *space_after_code = strextract(unparsed_string, 
            parsed_error_code + sizeof("Code ") - 1, /* The magic */
            parsed_error_code, " "); // Note the space

// Explanation: strextract only expects a pointer to a buffer that is large enough
// to store the parsed result. If we pass in a location later in the buffer, the
// function will treat that exactly like if it was the beginning of the buffer so to
// only modify the part that we want.. the ## location of the buffer. The -1 is 
// necessary because the sizeof operator includes the null character in c strings.

char parsed_error_msg[32] = {'\0'};

// Copy the message til the end
strextract(space_after_code, parsed_error_msg, " ", "\r"); 

printf("Error code: %s\n", parsed_error_code); // Error code: Code 09
printf("Message: %s\n", parsed_error_msg);     // Message: This is a test message

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants