Ad

Suppose you have a string that looks something like this "1 + 2 * (2 - (3.1415 / 2.7^(2.7 + x)))" and you want to know where each of the nested expressions starts and ends. You can use ParseNestedness().

ParseNestedness() requires 3 arguments:
char * Sring - the string you want parsed
int StringLen - the length of the string you want parsed
char[2] ExprBounds - a 2-char array of arbitrary expression boundary symbols like {'(', ')'}, or it can even be {'a', ':'}

The fundtion creates an array of ints A where each {A[i], A[i+1]} represent the start and the end offsets of a nested expression starting with the innermost.

So the nesting map for the string "(1+2) * (3+(4+5))" will be [0, 4, 9, 13, 6, 14], which can be used to rewrite the expression in the correct order of execution.

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

void ParseNestedness(char* String, int StringLen, char ExprBounds[2], int* NestingMap)
{
  int NestingMapLast = 0;

  int BoundsStack[StringLen];
  int BoundsStackLast = 0;

  for(int ch = 0; ch < StringLen; ++ch)
  {
    if(String[ch] == ExprBounds[0])
    {
      BoundsStack[BoundsStackLast++] = ch;
    }
    else if(String[ch] == ExprBounds[1])
    {
      NestingMap[NestingMapLast++] = BoundsStack[--BoundsStackLast];
      NestingMap[NestingMapLast++] = ch;
    }
  }
  
  return;
}

int main()
{
  char* TestString = "(-1+0)*(1+(2+(3+4)))*(5+6)";
  char  ExprBounds[2] = {'(', ')'};

  int* NestingMap = (int*)malloc(sizeof(int) * 10);

  ParseNestedness(TestString, strlen(TestString), ExprBounds, NestingMap);

  for(int i = 0; i < 10; ++i)
  {
    printf("%i ", NestingMap[i]);
  }
  printf("\n");
  
  return 0;
}