代码之家  ›  专栏  ›  技术社区  ›  vehomzzz

如何从字符串结尾提取数字

  •  7
  • vehomzzz  · 技术社区  · 14 年前

    给定如下字符串:

       sdfsd34 
        sdfdsf1
    

    34,1个 使用c++(STL但没有boost),c。

    谢谢

    7 回复  |  直到 14 年前
        1
  •  26
  •   Konrad Rudolph    14 年前

    你在找函数 string.find_last_not_of :

    string str = "sdfsd34";
    size_t last_index = str.find_last_not_of("0123456789");
    string result = str.substr(last_index + 1);
    
        2
  •  4
  •   Jerry Coffin    14 年前

    std::string find_last_not_of 内置,任何人谁喜欢弦式操纵。

    如果愿意,可以更像容器那样处理字符串,并从末尾开始查找第一个非数字:

    std::string::iterator pos = std::find_if(
        mystring.rbegin(), 
        mystring.rend(), 
        std::not1(std::isdigit)).base();
    

    在这种情况下,从 reverse_iterator iterator 碰巧做得很好。这个 逆迭代器 返回者 find_if 将引用最后一个元素 字符串末尾的连续数字集。这个 base mystring.end() 如果结尾没有数字,或者(不幸的是)整个字符串由数字组成。

        3
  •  2
  •   Steve Townsend    14 年前

    初始版本,使用 <algorithm> :

    string input("aasdf43");
    string matches("01234567890");
    
    string::iterator iter = find_first_of(input.begin(), input.end(), 
            matches.begin(), matches.end());
    
    string next(iter, input.end());
    
    stringstream intStream(next);
    int intValue;
    intStream >> intValue;
    

    string input("aasdf43");
    string matches("0123456789");
    size_t offset = input.find_first_of(matches);
    string next(input.substr(offset));
    
    stringstream intStream(next);
    int intValue;
    intStream >> intValue;
    

    只是为了更好的衡量-一个 <算法> 与所有数字相比不需要检查的版本。

    string::reverse_iterator iter = find_if_not(input.rbegin(), input.rend(), 
        ([&](char c) { return c >= '0' && c <= '9';}));
    reverse(input.rbegin(), iter);
    string reversed(input.rbegin(), iter);
    
    stringstream intStream(reversed);
    int intValue;
    intStream >> intValue;
    
        4
  •  2
  •   Vatsan    14 年前

    这是C解。你必须包括stdio.h和ctype.h才能让这个工作。

    char* str = "djafldjsalj124"; 
    long n; 
    
    char *s = str; 
    while (*s && !isdigit(*s)) s++; 
    if (*s)
    {
     sscanf(s, "%d", &n);  
     printf("%d\n", n); 
    }
    
        5
  •  1
  •   miked    14 年前

        6
  •  0
  •   frankc    14 年前

    已经发布的C++解决方案非常合理。在C语言中,可以使用strpbrk。这将第一次出现一组字符中的任何一个,因此如果不能保证数字出现在字符串的末尾,则需要调用strpbrk,直到它返回空值,并在下一次调用之前保存上一次调用的结果。至少据我所知,没有像strchr那样的反向strpbrk。

        7
  •  0
  •   Yuliy    14 年前

    假设str是有问题的字符串,我将包含一个指向数字开头字符的指针。。。

    char* i;
    for(i = str + strlen(str) - 1; i >= str && *i >= '0' && *i <= '9'; i--);
    i++;