Given the text "for (anything)" How to skip everything in front of '(' and ')', i.e. before the first bracket there can be any number of spaces, and inside the bracket everything that is important is to have opening and closing brackets, not paying attention what's inside

  • one
    Here's how to ask questions! - Igor

2 answers 2

Anyway, faster than running through the array from the beginning to the first ")" after "(" you can’t think of anything. Library functions don’t work faster, only you lose time on the call. Just run a cycle, meet "(check the box, meet) "check the box if there is all stop.

int i = 0; int flag = 0; for (i = 0 ; i < lenght; i++) { if(str[i] == '(') flag = 1; if((str[i] == ')') && (flag == 1)) { flag = 2; break; } } //тут по значению флага определяете нашли вы скобку или нет, //по значению i определяете позицию скобки 

    If you do not need to analyze the balance of brackets, then the easiest way is to use the strchr () / strrchr () functions to find the opening and closing brackets.

    This can be arranged in the form, for example, here's a demo program:

     #include <stdio.h> #include <stdlib.h> #include <string.h> struct pp { const char *lp, *rp; }; // возвращает структуру с указателями на первую `(` и последнюю `)` скобки struct pp str_get_parenthesis (const char *str) { struct pp res = {strchr(str, '('), strrchr(str, ')')}; return res; } int main (int ac, char *av[]) { char *str = 0; size_t len; while (getline(&str, &len, stdin) != -1) { struct pp p = str_get_parenthesis(str); if (p.lp && p.rp && p.rp > p.lp) printf("%.*s\n", (int)(p.rp - p.lp + 1), p.lp); else puts("Can't locate (...)"); } free(str); return puts("End") == EOF; } 

    By slightly changing the function and data structure of the search result, you can search for the most balanced brackets:

     struct ppb { const char *lp, *rp; int cnt; // показатель баланса -- 0 все скобки закрыты }; struct ppb str_balanced_parenthesis (const char *str) { struct ppb res = {strchr(str, '('), 0, 0}; if (res.lp) { res.cnt = 1; for (const char *p = res.lp + 1; *p && res.cnt; p++) if (*p == '(') res.cnt++; else if (*p == ')') { res.cnt--; res.rp = p; } } return res; } 

    You can use it as follows (as in the example above):

     ... struct ppb p = str_balanced_parenthesis(str); if (p.lp && p.rp) printf("cnt = %d [%.*s]\n", p.cnt, (int)(p.rp - p.lp + 1), p.lp); else puts("Can't locate (...)"); ....