Matches nested brackets and returns the location after the end of a bracket that matched the current location.

View versions (1)

Interface

#include <codecogs/strings/search/detect_bracket.h>

using namespace Strings::Search;

This functions performs two tasks

  • Firstly is detects if the character at the current string position is the openning bracket. If not it simply returns the current location, offset
  • If it is, it then searches for the corresponding closing bracket, allowing for a nested structure of brackets. It will also skip over comments and text enclosed in speach marks.

The function was designed for analysing C programs, however with the exception of the comment structure (see detect_comments), this routine could be used on most other languages.

Example 1

Detecting '{..}' in C code

#include <codecogs/strings/search/detect_bracket.h>

int main()
{
  const char str[]="for(int i=1;i<10) { if(i==2) { printf(\"{%d}\",i) }else { printf('}') } } printf(\"the end of { detection }...\");";

  printf("\nClosing bracket when starting at str[%d] is %d", 5, detect_bracket(str, 5, strlen(str)));

  printf("\nClosing bracket when starting at str[%d] is %d", 18, detect_bracket(str, 18, strlen(str)));

  printf("\nClosing bracket when starting at str[%d] is %d", 39, detect_bracket(str, 39, strlen(str)));	

  return 0;
}

Output:

Closing bracket when starting at str[5] is 5
Closing bracket when starting at str[18] is 71
Closing bracket when starting at str[39] is 43

Example 2

Detecting '<..>' in html

#include <codecogs/strings/search/detect_bracket.h>

int main()
{
  const char str[]="<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td> </td>";

  printf("\nClosing bracket when starting at str[%d] is %d", 0, detect_bracket(str, 0, strlen(str), '<', '>'));

  printf("\nClosing bracket when starting at str[%d] is %d", 18, detect_bracket(str, 18, strlen(str), '<', '>'));

  printf("\nClosing bracket when starting at str[%d] is %d", 39, detect_bracket(str, 39, strlen(str), '<', '>'));	

  return 0;
}

Output:

Closing bracket when starting at str[0] is 50
Closing bracket when starting at str[18] is 18
Closing bracket when starting at str[50] is 54

Parameters

str
The input string containing the text to analyse
offset
An offset into the str. If str[offset] does not correspond to the open character for a bracket, then offset is returned by this function.
str_len
The length of the str, or the total length over which to search. Use strlen if you are unsure.
open
The character that defines an open bracket. Default Value = '{'
close
The character that defines a closed bracket. Default Value = '}'
GPL Licence — free for non commercial use. See Licence details.