【发布时间】:2021-11-26 21:45:11
【问题描述】:
美好的一天,我正在努力寻找代码来解析字符并仅实现''之间的内容。在这种情况下,我有:
Char Character = "'2'; 0x32"
在这里,我只想从字符串中提取 2 并将其保存到另一个变量中。如果有人可以为我提供执行此操作的代码,将不胜感激!
【问题讨论】:
标签: string parsing char extract
美好的一天,我正在努力寻找代码来解析字符并仅实现''之间的内容。在这种情况下,我有:
Char Character = "'2'; 0x32"
在这里,我只想从字符串中提取 2 并将其保存到另一个变量中。如果有人可以为我提供执行此操作的代码,将不胜感激!
【问题讨论】:
标签: string parsing char extract
在 C++ 中你可以这样写:
#include <stdio.h> // for sscanf
int main()
{
// your string
const char *text = "'2'; 0x32";
// your variable
int variable;
// a working variable, to be set to the number of characters matched by sscanf
int used;
// match the patter on a single quote followed by an integer
// if that integer is found, its value will be written to `variable`
// then write the used characters into `used` working variable
// the result from the function is 1, when the variable was found
if (sscanf(text, "'%d%n", &variable, &used) != 1)
{
// explain to the user that there is a syntax error
printf("Invalid input: expecting \"^'[0-9]+'(.*)\"");
// exit with an error
return 1;
}
// confirm that after the integer there is a single quote
if (text[used] != '\'')
{
// explain to the user that there is a syntax error
printf("An integer was found, but no trailing single quote exists.");
// exit with an error
return 2;
}
// success
printf("The integer enclosed in the single quotes is %d", variable);
// exit without errors
return 0;
}
【讨论】: