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

Getting a substring between two tags C/C++

本文关键字:C++ 之间 字符串 两个 获取      更新时间:2023-10-16

你好,我正在C/C++中创建一个排序分析器。这很简单,我只想使用C/C++从标签"(" and ")"中获取一个字符串。我知道逻辑就像查找第一个标签,并在找到下一个标签之前,每找到一个字符就增加一个数字。但我的逻辑很糟糕,所以如果有人能给我一个功能,它会有所帮助。

编辑:我看到C/C++字符串函数完全不同,所以只有C++可以。

您似乎不确定C和C++中的字符串处理之间的区别。你的描述似乎意味着你想用C风格来做这件事。

void GetTag(const char *str, char *buffer)
{
    buffer[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 = '';
            break;
        }
        else if (copy)
        { 
            *y = *x;
            y++;
        }
        ++x;
    }
}

或者,C++的方法是使用std::字符串,这更安全,因为它不会篡改指针,而且可以说更容易阅读和理解。

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 "";
}