测试字符串以查看是否存在数字并将该值分配给变量,同时跳过所有非数字值?

发布于 2024-08-24 07:21:03 字数 572 浏览 6 评论 0原文

给定一个字符串“a 19 bcd 20”,我如何测试字符串上的特定位置是否有一个数字? (不仅仅是字符“1”,而是整个数字“19”和“20”)。

char s[80];
strcpy(s,"a 19 b c d 20");

int i=0;
int num=0;
int digit=0;
for (i =0;i<strlen(s);i++){
    if ((s[i] <= '9') && (s[i] >= '0')){    //how do i test for the whole integer value not just a digit

        //if number then convert to integer
        digit = s[i]-48;
        num = num*10+digit;
    }

    if (s[i] == ' '){
        break; //is this correct here? do nothing
    }
    if (s[i] == 'a'){
       //copy into a temp char
    }
}

given a string say " a 19 b c d 20", how do I test to see if at that particular position on the string there is a number? (not just the character '1' but the whole number '19' and '20').

char s[80];
strcpy(s,"a 19 b c d 20");

int i=0;
int num=0;
int digit=0;
for (i =0;i<strlen(s);i++){
    if ((s[i] <= '9') && (s[i] >= '0')){    //how do i test for the whole integer value not just a digit

        //if number then convert to integer
        digit = s[i]-48;
        num = num*10+digit;
    }

    if (s[i] == ' '){
        break; //is this correct here? do nothing
    }
    if (s[i] == 'a'){
       //copy into a temp char
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

凉城凉梦凉人心 2024-08-31 07:21:03

这些是 C 解决方案:

您只是想从字符串中解析数字吗?然后您可以使用 strtol() 遍历字符串。

long num = 0;
char *endptr = NULL;
while (*s) {
  num = strtol(s, &endptr, 10);
  if (endptr == s) { // Not a number here, move on.
    s++;
    continue;
  }
  // Found a number and it is in num. Move to next location.
  s = endptr;
  // Do something with num.
}

如果您有具体位置和号码需要检查,您仍然可以执行类似的操作。
例如:“19”在位置 10 吗?

int pos = 10;
int value = 19;
if (pos >= strlen(s))
  return false;
if (value == strtol(s + pos, &endptr, 10) && endptr != s + pos)
  return true;
return false;

您是否尝试在不使用任何库例程的情况下解析这些数字?

注意:我没有测试过这个......

int num=0;
int sign=1;
while (*s) {
  // This could be done with an if, too.
  switch (*s) {
    case '-':
      sign = -1;
    case '+':
      s++;
      if (*s < '0' || *s > '9') {
        sign = 1;
        break;
      }
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
      // Parse number, start with zero.
      num = 0;
      do {
        num = (num * 10) + (*s - '0');
        s++;
      } while (*s >= '0' && *s <= '9');
      num *= sign;
      // Restore sign, just in case
      sign = 1;
      // Do something with num.
      break;
    default:
      // Not a number
      s++;
  }
}

These are C solutions:

Are you just trying to parse the numbers out of the string? Then you can just walk the string using strtol().

long num = 0;
char *endptr = NULL;
while (*s) {
  num = strtol(s, &endptr, 10);
  if (endptr == s) { // Not a number here, move on.
    s++;
    continue;
  }
  // Found a number and it is in num. Move to next location.
  s = endptr;
  // Do something with num.
}

If you have a specific location and number to check for you can still do something similar.
For example: Is '19' at position 10?

int pos = 10;
int value = 19;
if (pos >= strlen(s))
  return false;
if (value == strtol(s + pos, &endptr, 10) && endptr != s + pos)
  return true;
return false;

Are you trying to parse out the numbers without using any library routines?

Note: I haven't tested this...

int num=0;
int sign=1;
while (*s) {
  // This could be done with an if, too.
  switch (*s) {
    case '-':
      sign = -1;
    case '+':
      s++;
      if (*s < '0' || *s > '9') {
        sign = 1;
        break;
      }
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
      // Parse number, start with zero.
      num = 0;
      do {
        num = (num * 10) + (*s - '0');
        s++;
      } while (*s >= '0' && *s <= '9');
      num *= sign;
      // Restore sign, just in case
      sign = 1;
      // Do something with num.
      break;
    default:
      // Not a number
      s++;
  }
}
筱武穆 2024-08-31 07:21:03

看起来你想解析字符串并从中提取所有数字;如果是这样,这里有一个更“C++”的方法:

string s = "a 19 b c d 20"; // your char array will work fine here too
istringstream buffer(s);
string token;
int num;
while (!buffer.eof())
{
    buffer >> num; // Try to read a number
    if (!buffer.fail()) {    // if it doesn't work, failbit is set
        cout << num << endl; // It's a number, do what you want here
    } else {
        buffer.clear();  // wasn't a number, clear the failbit
        buffer >> token; // pull out the non-numeric token
    }
}

这应该打印出以下内容:

19 
20

流提取运算符自动提取空格分隔的标记,因此您不必执行任何混乱的字符级操作或手动操作整数转换。您需要为 stringstream 类添加 #include

It seems like you want to parse the string and extract all the numbers from it; if so, here's a more "C++" way to do it:

string s = "a 19 b c d 20"; // your char array will work fine here too
istringstream buffer(s);
string token;
int num;
while (!buffer.eof())
{
    buffer >> num; // Try to read a number
    if (!buffer.fail()) {    // if it doesn't work, failbit is set
        cout << num << endl; // It's a number, do what you want here
    } else {
        buffer.clear();  // wasn't a number, clear the failbit
        buffer >> token; // pull out the non-numeric token
    }
}

This should print out the following:

19 
20

The stream extraction operator pulls out space-delimited tokens automatically, so you're saved from having to do any messy character-level operations or manual integer conversion. You'll need to #include <sstream> for the stringstream class.

夏花。依旧 2024-08-31 07:21:03

您可以使用 atoi()

You can use atoi().

若沐 2024-08-31 07:21:03

if 之后,您需要转移到 while 来收集后续数字,直到遇到非数字。

但是,更重要的是,您是否明确定义了您的要求?数字之间允许有空格吗?如果有两个数字(例如 abc123def456gh)怎么办?

after your if you need to shift to while to collect subqsequent digits until you hit a non-digit.

BUT, more inportantly, have you clearly defined your requirements? Will you allow whitespace between the digits? What if there are two numbers, like abc123def456gh?

唔猫 2024-08-31 07:21:03

它不是很清楚你在寻找什么。假设你想从字符串中提取所有数字,然后从找到的数字中提取整个数字,你可以尝试以下操作:

    int i;
    unsigned long num=0; // to hold the whole number.
    int digit;
    for (i =0;i<s[i];i++){
            // see if the ith char is a digit..if yes extract consecutive digits
            while(isdigit(s[i])) { 
                    num = num * 10 + (s[i] - '0');
                    i++;
            }
    }

假设字符串中的所有数字连接时从整数到整数不会溢出长数据类型。

Its not very clear what you are looking for.. Assuming you want to extract all the digits from a string and then from a whole number from the found digits you can try the following:

    int i;
    unsigned long num=0; // to hold the whole number.
    int digit;
    for (i =0;i<s[i];i++){
            // see if the ith char is a digit..if yes extract consecutive digits
            while(isdigit(s[i])) { 
                    num = num * 10 + (s[i] - '0');
                    i++;
            }
    }

It is assumed that all the digits in your string when concatenated to from the whole number will not overflow the long data type.

×纯※雪 2024-08-31 07:21:03

没有办法测试整数。正如您所做的那样,编写词法分析器是一种方法。另一种方法是尝试使用 C 标准库的 strtoul 函数(或一些类似的函数,具体取决于字符串是否具有浮点数等)。

您的代码需要允许空格,并且您可以使用 C 库的 isdigit 来测试当前字符是否是数字:

vector<int> parse(string const& s) {
     vector<int> vi;
     for (size_t i = 0; i < s.length();) {
         while (::isspace((unsigned char)s[ i ]) i++;
         if (::isdigit((unsigned char)s[ i ])) {
              int num = s[ i ] - '0';
              while (::isdigit((unsigned char)s[ i ])) {
                 num = num * 10 + (s[ i ] - '0');
                 ++i;
              }
              vi.push_back(num);
         }
                ....

另一种方法是使用 boost::lexical_cast >:

 vector<string> tokenize(string const& input) {
     vector<string> tokens;
     size_t off = 0, start = 0;
     while ((off = input.find(' ', start)) != string::npos) {
          tokens.push_back(input.substr(start, off-start));
          start = off + 1;
     }
     return tokens;
 }

 vector<int> getint(vector<string> tokens) {
      vector<int> vi;
      for (vector<string> b = tokens.begin(), e = tokens.end(); b! = e; ++b) {
         try
         {
           tokens.push_back(lexical_cast<short>(*b));
         }
         catch(bad_lexical_cast &) {}
      }
      return vi;
 }

There's no way to test for a whole number. Writing a lexer, as you've done is one way to go. Another would be to try and use the C standard library's strtoul function (or some similar function depending on whether the string has floating point numbers etc).

Your code needs to allow for whitespaces and you can use the C library's isdigit to test if the current character is a digit or not:

vector<int> parse(string const& s) {
     vector<int> vi;
     for (size_t i = 0; i < s.length();) {
         while (::isspace((unsigned char)s[ i ]) i++;
         if (::isdigit((unsigned char)s[ i ])) {
              int num = s[ i ] - '0';
              while (::isdigit((unsigned char)s[ i ])) {
                 num = num * 10 + (s[ i ] - '0');
                 ++i;
              }
              vi.push_back(num);
         }
                ....

Another approach will be to use boost::lexical_cast:

 vector<string> tokenize(string const& input) {
     vector<string> tokens;
     size_t off = 0, start = 0;
     while ((off = input.find(' ', start)) != string::npos) {
          tokens.push_back(input.substr(start, off-start));
          start = off + 1;
     }
     return tokens;
 }

 vector<int> getint(vector<string> tokens) {
      vector<int> vi;
      for (vector<string> b = tokens.begin(), e = tokens.end(); b! = e; ++b) {
         try
         {
           tokens.push_back(lexical_cast<short>(*b));
         }
         catch(bad_lexical_cast &) {}
      }
      return vi;
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文