简体   繁体   English

从字符串中提取特定的文本模式

[英]Extract a specific text pattern from a string

I have a string as follows, 我有一个字符串如下

"0/41/9/71.94 PC:0x82cc (add)" “ 0/41/9 / 71.94 PC:0x82cc(添加)”

The desired output is the text between the brackets ( ) 所需的输出是方括号()之间的文本

Ex: output = add, 例如:输出=添加,

for the string specified above 对于上面指定的字符串

How is this done using sscanf? 如何使用sscanf完成此操作? Is there a better way to do it in C++? 在C ++中有更好的方法吗?

With string operations exclusively: 仅使用string操作:

std::string text = "0/41/9/71.94 PC:0x82cc (add)";

auto pos = text.find('(') + 1;
auto opcode = text.substr(pos, text.find(')', pos) - pos);

Demo . 演示

With sscanf it would look something like this: 使用sscanf ,它将看起来像这样:

std::string opcode(5, '\0'); // Some suitable maximum size

sscanf(text.c_str(), "%*[^(](%[^)]", &opcode[0]);

Demo . 演示

Its very easy, u should try yourself, think how to search in an array, then think if i could compare the content of an array or not, then every thing would be possible, as a programmer u have to create ideas, however if i were asked to write a program like this i would do that as follows: 这很容易,您应该尝试一下,考虑如何在数组中进行搜索,然后考虑是否可以比较数组的内容,那么一切都会成为可能,因为程序员您必须创建想法,但是如果我被要求编写这样的程序,我将按照以下步骤进行操作:

int i=0, p=0;
char string="0/41/9/71.94 PC:0x82cc (add)", nstr[100];
while(string[i]!='\0')
{
while(string[i]!='(')
i++;
if (string[i]=='(')
{
i++;
goto end;
}
end:
while (string[i]!=')' || string[i]!='\0')
{
nstr[p]=string[i];
p++;
i++;
}
nstr[p]='\0';
cout<<Output = "<<nstr<<"\n";

I know this is very long, but this will give you deeper understanding of parsing or spliting a string, hope i help u, thank u... 我知道这很长,但这将使您对解析或拆分字符串有更深入的了解,希望我能帮助您,谢谢...

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

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