Search code examples
c++arraysloopsdata-conversionternary

Boolean Function to Evaluate string


I need to build a function that evaluates a string of numbers in C++. The string of numbers is in the balanced ternary form meaning the numbers are either -1,0,or 1 to be valid. So the point of the function is to check the string to make sure it is valid. For example, if a user enters "-101-11" The boolean function would return true. Or if the user enters "-1012" The boolean function would return false. This function is also a private member function of a class. Let me show you what I've coded so far, (I know it's incorrect but if someone could help me out that would be great!) It's in C++.

bool BTernary::isTernary(string s)
{
    int i;
    int l = s.length();
    for (i = 0; i < l; i++) {
        if (s.at(i) == '-') {
            continue;
        }
        else if (s.at(i) == '0') {
            continue;
        }
        else if (s.at(i) == '1') {
            break;
        }

        return true;
    }

    return false;
}

I've also tried a different approach to checking the string, it looks like this: (This is in a test file I've been working on for awhile and it compiles without error. The problem is if it sees a '-' or a '1' or a '0' it automatically assumes it to be true, I guess instead of evaluating the whole string for the characters I need to evaluate character by character?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int i;
    string s = "0";
    for (i = 0; i < s.length(); i++) {
        if (s.at(i) == '-' || '0' || '1') {
            cout << "True" << endl;
            return True;
        }
        else {
            cout << "false" << endl;
            return false;
        }
    }
}

Solution

  • Here's a terser version of Mihail's suggestion:

    bool BTernary::isTernary(const std::string& s)
    {
        bool minus = false;
    
        for (const char c : s)
        {
           switch (c)
           {
             case '-':
                if (minus) return false;
                minus = true;
                break;
    
             case '0':
                if (minus) return false;
                break;
    
             case '1':
                if (minus) minus = false;
                break;
    
             default:
                return false;
        }
    
        return !minus;
    }