获取两个标签C / C ++之间的子字符串

时间:2013-06-23 02:36:12

标签: c++

你好我在C / C ++中创建了一个解析器它很简单我只是希望能够使用C / C ++从标签"(" and ")"获取一个字符串我知道逻辑就像找到第一个标记并递增每个找到的单个字符的数字,直到找到下一个标记。但是,如果某人至少可以给我一个可以提供帮助的功能,那么我就会误解一个逻辑。

编辑:我看到C / C ++字符串函数没有什么相似之处所以只有C ++会这样做。

1 个答案:

答案 0 :(得分:0)

您似乎不确定C和C ++中字符串处理之间的区别。您的描述似乎意味着希望以C风格的方式进行。

void GetTag(const char *str, char *buffer)
{
    buffer[0] = '\0';
    char *y = &buffer[0];

    const char *x = &str[0];
    bool copy = false;

    while (x != NULL)
    {
        if (*x == '(')
            copy = true;
        else if (*x == ')' && copy)
        {
            *y = '\0';
            break;
        }
        else if (copy)
        { 
            *y = *x;
            y++;
        }
        ++x;
    }
}

或者,C ++的方法是使用更安全的std :: string,因为它不是在摆弄指针,而且更容易阅读和理解。

std::string GetTag(const std::string &str)
{
    std::string::size_type start = str.find('(');
    if (start != str.npos)
    {
        std::string::size_type end = str.find(')', start + 1);
        if (end != str.npos)
        {
            ++start;
            std::string::size_type count = end - start;
            return str.substr(start, count);
        }
    }
    return "";
}