Skip to content

Instantly share code, notes, and snippets.

@IngwiePhoenix
Last active March 20, 2016 22:43
Show Gist options
  • Select an option

  • Save IngwiePhoenix/1a060d80469390b2c142 to your computer and use it in GitHub Desktop.

Select an option

Save IngwiePhoenix/1a060d80469390b2c142 to your computer and use it in GitHub Desktop.
Paranthese counting
#include <stdio.h>
#include <string.h>
/**
* @author: Jan P. B.
* Purpose: Count parentheses in a string.
* Used to count capture groups for SLRE - and as string practice for Jan. :)
*
* @param {char*} c : Buffer
* @param {int} len : Buffer length
* @return {int} Number of parenthesis, -1 on error.
*
* @NOTE: Might want to comment out the printf()s, or throw some kind of exception...
*/
int countbrackets(char* c, int len) {
char prevchar=' ';
int braop=0;
int bracl=0;
for(int i=0; i<len; i++) {
if (c[i]=='(' && prevchar!='\\') {
braop++;
} else if (c[i]==')' && prevchar!='\\') {
bracl++;
}
prevchar = c[i];
}
if (braop==bracl) {
return braop;
} else {
if (braop>bracl)
printf("es gibt mehr ( wie )");
else {
printf("es gibt mehr ) wie (");
return -1;
}
}
// Silencing "Function reaching end of control"
return -1;
}
int main() {
char* pattern = "(\\d).(\\d).(\\d) \\((.+)\\)\0";
int len = strlen(pattern);
int pars = countbrackets(pattern, len);
printf(
"String: %s\nLen: %i\nPars:%i\n",
pattern, len, pars
);
}
/*
Expecting:
(\d).(\d).(\d) \((.+)\)
^^^^ ^^^^ ^^^^ ^^^^ = 4
Output:
[email protected]_W723_V_Typ_A_1_01_012 /tmp $ gcc pars.c -o pars; and ./pars
String: (\d).(\d).(\d) \((.+)\)
Len: 23
Pars:4
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment