简体   繁体   English

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

[英]Getting a substring between two tags C/C++

Hello I am creating a parser of sorts in C/C++ it is rather simple i just want to be able to get a string from to tags "(" and ")" using C/C++ i know that the logic is like find first tag and increment a number every single char that is found until the next tag is found. 您好,我正在C / C ++中创建各种解析器,这很简单,我只想能够使用C / C ++从标签"(" and ")"获取字符串,我知道逻辑就像查找第一个标签一样并为找到的每个字符增加一个数字,直到找到下一个标签。 But i suck a logic so if someone could at least give me a function that could help. 但是我吸了一个逻辑,所以如果有人至少可以给我一个可以提供帮助的功能。

Edit:I see that C/C++ string functions are nothing alike so just C++ will do. 编辑:我看到C / C ++字符串函数完全不同,所以只有C ++可以。

You seem unsure of the differences between string handling in C and in C++. 您似乎不确定C和C ++中字符串处理之间的区别。 Your description seems to imply wanting to do it in a C-style way. 您的描述似乎暗示要以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;
    }
}

Alternatively, the C++ way is to use the std::string which is safer because it's not fiddling with pointers, and arguably easier to read and understand. 另外,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 "";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM