Sara
Sara

Reputation: 2436

String handling in c

Here is my code

char* a[10];
a[0]="'example'";
char* p;
p=strstr(a[0],"'");

I know if strstr can find the ' it returns a pointer which points to first character which is '. I want to take the value between two ' and save it in a[1]. how should I do that? As a result a[1] is "example".

Upvotes: 0

Views: 140

Answers (2)

Daniel Fischer
Daniel Fischer

Reputation: 183888

Just find the next occurrence of ' and copy the substring:

char* a[10];
a[0]="'example'";
char* p, *q;
p=strstr(a[0],"'");
if (p) {
    q = strstr(p+1, "'");
    if (q) {
        size_t len = (size_t)(q - p);
        char *sub = malloc(len + 2);
        if (!sub) {
            /* Oops */
            exit(EXIT_FAILURE);  /* Something more sensible rather */
        }
        memcpy(sub, p, len+1);
        sub[len+1] = 0;
        a[1] = sub;
     }
     else {
         a[1] = NULL;
     }
}
else {
    a[1] = NULL;
}

Note that in this case, it would be better to use strchr to find the single character.

Upvotes: 1

hmjd
hmjd

Reputation: 121971

strchr() seems a more appropriate choice that strstr().

Use the result of first strchr(), + 1, as the argument to a subsequent strchr() and then malloc() and strcpy() or sprintf() into a[1]:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char* a[10];
    char* p;

    a[0] = "'example'";

    p = strchr(a[0], '\'');
    if (p)
    {
        char* q = strchr(++p, '\'');
        if (q)
        {
            a[1] = malloc((q - p) + 1);
            if (a[1])
            {
                sprintf(a[1], "%.*s", q - p, p);
                printf("[%s]\n", a[1]);
            }
        }
    }
    return 0;
}

Storing pointers to string literals and malloc() data into the same array seems a dangerous thing to do. You must free() dynamically allocated memory, but only dynamically allocated memory. The code will need to know what elements in a are pointing at dynamically allocated memory, and must be free()d, and those that are not.

Initialise a to all NULLs, so it is known what elements are populated:

char* a[10] = { NULL };

and calling free() on a NULL pointer is safe (does nothing).

Upvotes: 2

Related Questions