Jack Trowbridge
Jack Trowbridge

Reputation: 3251

Parsing char array

I've got a char array as follows:

char* test = "+IPD,308:{data:\"abc\"} UNLINK";

I'm trying to parse it to return the chunk from { to }, so in this case the substring {data:\"abc\"}.

I've used strchr() and strrchr() which return a pointer to the location of a single character; but how would I use this to return {data:\"abc\"} in this case?

Upvotes: 1

Views: 203

Answers (2)

abelenky
abelenky

Reputation: 64682

Try this:

const char* input = "+IPD,308:{data:\"abc\"} UNLINK";
char* start = strchr(input, '{');           // result should be input[9]
char* end = strrchr(input, '}');            // result should be input[20]

char* output = (char*)malloc(end-start+2);  // End-start should be 11 + 2 = 13
strncpy(output, start, end-start+1);        // Copy 12 chars.
output[end-start+1] = '\0';                 // Append an End-of-String nul

/* Use the output string.... */

free(output);                               // Very important cleanup!
output = NULL; 

It finds the first brace, the final brace, allocates appropriate memory, and does a strncpy to make a new string with the relevant data.

IDE Link: http://ideone.com/sVn147

Output: {data:"abc"}

Upvotes: 2

Tripp Kinetics
Tripp Kinetics

Reputation: 5439

You could try to iterate through the string. When you reach the first token, start copying characters into a second buffer. Break out of the loop when you reach the second token.

Upvotes: 0

Related Questions