通过一个字符串和提取的数字? [英] going through a string of characters and extracting the numbers?

查看:158
本文介绍了通过一个字符串和提取的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串,如何通过它,并将该字符串中的所有数字分配到一个整数变量,而不是所有其他字符?

Given a string of characters, how can I go through it and assign all the numbers within that string into an integer variable, leaving out all other characters?

当有一个字符串已经通过 gets()读入,而不是当读取输入时,要执行此任务。

I want to do this task when there is a string of characters already read in through gets(), not when the input is read.

推荐答案

unsigned int get_num(const char* s) {
  unsigned int value = 0;
  for (; *s; ++s) {
    if (isdigit(*s)) {
      value *= 10;
      value += (*s - '0');
   }
  }
  return value;
}






/ strong>:这是一个更安全的版本的函数。
如果 s NULL 或者根本不能转换为数值,则返回0。如果字符串表示大于 UINT_MAX 的值,则返回 UINT_MAX


Edit: Here is a safer version of the function. It returns 0 if s is NULL or cannot be converted to a numeric value at all. It return UINT_MAX if the string represents a value larger than UINT_MAX.

#include <limits.h>

unsigned int safe_get_num(const char* s) {
  unsigned int limit = UINT_MAX / 10;
  unsigned int value = 0;
  if (!s) {
    return 0;
  }
  for (; *s; ++s) {
    if (value < limit) {
      if (isdigit(*s)) {
        value *= 10;
        value += (*s - '0');
      }
    }
    else {
      return UINT_MAX;
    }
  }
  return value;
}

这篇关于通过一个字符串和提取的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆