检查字符串是否以(%i)结尾,然后将该数字赋给一个变量

Check if string ends with (%i) then assign that number in a variable

本文关键字:数字 变量 一个 然后 是否 字符串 结尾 检查      更新时间:2023-10-16

假设我有一个字符串"MyName(10)"
我想检查以(%i)结尾的字符串,并在变量中分配该数字。
我试过sscanf,但它不起作用。

sscanf("MyName(10), "%s(%i)", tempName, &count);

tempNamecountMyName(10)的存储为0

MyName可以是可变长度,它不是固定的"MyName",它可以是"Mynaaaaaame"

试试这个示例代码。也许这能帮上忙……你可以根据你的需要做任何调整

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define IS_DIGIT(x) 
    ( x == '0' || x == '1' || x == '2' || 
      x == '3' || x == '4' || x == '5' || x == '6' || 
      x == '7' || x == '8' || x == '9' )

/* the function will return 0 in success and -1 in error */
/* on success num will contain the pointer to the number */
int 
check_last_num(char * str , int * num)
{
    int len = strlen(str);
    int index = len - 1;
    /* make sure the last char is ')' */
    if (str[index] != ')')
    return -1;
    while ( --index  >= 0 && (str[index] != '(') ) {
    char c = str[index];
    if ( ! IS_DIGIT(c) )
        return -1;  
    }
    /* loop exit check */
    if (index < 0)
    return -1;
    *num = atoi((const char *) &str[index + 1]);
    return 0;
}
int main(int argc , char *argv[] )
{
    int rc ; 
    if ( 0 == check_last_num("MyName(890790)" , & rc))
    printf ("%d n" , rc);
    else 
    printf ("error n");
    return 0;
}
sscanf(Name, "%*[^(]%c%i%[^)]%*c", &var);

由于这被标记为c++,您可以这样做:

void assignVariable(std::string& s, std::string replace, int value)
{
    std::size_t pos;
    while ((pos = s.find(replace)) != std::string::npos)
        s.replace(pos, 2, std::to_string(value));
}
int main()
{
    std::string name = "%imyname(%i)%i";
    assignVariable(name, "%i", 365);
    std::cout << name;
    cin.get();
    return 0;
}

这将替换传递给函数的字符串中出现的所有replace。如果你想把它限制在最后一次出现,你可以使用std::string::find_last_of()