fredjohnson
fredjohnson

Reputation: 197

C - How do I print out characters between double quotes in a string array?

Suppose I have a character array as shown below:

char a[20] = "abc\"defg\"hij";  

How do I get it print defg ?

I thought of iterating through the array. When I find the first double quote, I begin printing the characters until another double quote is seen. It then breaks out of the loop. Is there a 'cleaner' way to achieve this?

Thanks for reading

Upvotes: 0

Views: 1431

Answers (4)

chqrlie
chqrlie

Reputation: 144969

Here is a simple way, that does not modify the source string:

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

int main(void) {
    char a[20] = "abc\"defg\"hij";  
    int n1 = strcspn(a, "\"");
    int n2 = (a[n1] == '\"') ? strcspn(a + n1 + 1, "\"") : 0;
    printf("%.*s\n", n2, a + n1);
    return 0;
}

Upvotes: 1

Emanuele Giona
Emanuele Giona

Reputation: 781

You can use the strtok method in string.h, which breaks the given string in tokens, given a delimiter.

In your example, you would use it like this:

/* set the `"` delimiter for the string `a` */
char *token;
token = strtok(a,"\"");

/* by printing out token now, you'd have `abc` as output */
/* but we want the second token */
token = strtok(NULL,"\"");

/* while using strtok any other time, you have to put NULL instead of the string you want to tokenize, as it maintains an internal buffer - extremely thread unsafe! */

printf("%s\n",token);
/* the output will be: defg */

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

You can use strchr(), like this

const char *head = strchr(a, '"');
if (head != NULL) {
    const char *tail = strchr(head + 1, '"');
    if (tail == NULL)
        tail = strchr(head + 1, '\0');
    fwrite(head + 1, 1, tail - head - 1, stdout);
    fputc('\n', stdout);
} 

But this works for very simple cases, you did not specify whether you needed a general solution or just a solution for this very case.

Upvotes: 2

campovski
campovski

Reputation: 3163

No, I think that your proposition is the cleanest. You could of course use strsep(), strchr() or regex.h but for your needs I think your solution is the cleanest. Everything else will result in a mess, there is no "one-liner" for this.

If you want to clean up, you can put your idea in another function that will return the string between the "", that will at least a bit clean up your main function.

Upvotes: 1

Related Questions