提取字符串之间的



你好,我正在努力寻找代码来解析一个字符,只实现' '之间的东西。在本例中,我输入:

Char Character = "'2'; 0x32"

这里我只想从字符串中提取2并将其保存到另一个变量。如果有人能为我提供这样的代码,我将不胜感激!

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