[Solved] How can I go about finding balance in a string in C?


Here is a demonstrative program written in C++ that you can use as an algorithm and rewrite it in C

#include <iostream>
#include <iomanip>
#include <stack>
#include <cstring>

bool balance( const char *s, std::stack<char> &st )
{
    const char *open  = "({[<";
    const char *close = ")}]>";

    if ( *s == '\0' )
    {
        return st.empty();
    }

    const char *p;

    if ( ( p = std::strchr( open, *s ) ) != nullptr )
    {
        st.push( *s );
        return balance( s + 1, st );
    }
    else if ( ( p = std::strchr( close, *s ) ) != nullptr )
    {
        if ( !st.empty() && st.top() == open[p-close] )
        {
            st.pop();
            return balance( s + 1, st );
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}   

int main() 
{

    for ( const char *s : { 
                            "()", "(())", "()()", "{()()}", "[]", "[()[]{}]()",
                            "{}}", "()[}", "[()}"

                          } )
    {
        std::stack<char> st;

        std::cout <<'\"' << s << "\" is balanced - "
                  << std::boolalpha << balance( s, st )
                  << std::endl;
    }


    return 0;
}

The program output is

"()" is balanced - true
"(())" is balanced - true
"()()" is balanced - true
"{()()}" is balanced - true
"[]" is balanced - true
"[()[]{}]()" is balanced - true
"{}}" is balanced - false
"()[}" is balanced - false
"[()}" is balanced - false

solved How can I go about finding balance in a string in C?