0

我想将字符串转换为整数。但我的字符串是 234,23,34,45。如果我使用 atoi,它只给我 234。我想转换我的字符串中的所有整数。我如何使用 atoi 来解决这个问题或什么可以我用代替atoi??

4

6 回答 6

4

一种选择是使用strtok () 将字符串分成几部分,然后在每个部分上使用 atoi()。

编辑:(由 dmckee 在评论中推荐)

  • 警告 #1:strtok 在调用之间保留一个指向字符串的指针;它不是线程安全的。
  • 警告 #2:strtok 会破坏传递给它的字符串,在标记末尾放置空字符来代替分隔符。
于 2010-12-21T21:20:39.907 回答
1

因为字符串只不过是一个 char * 在每次调用 atoi 到下一个 ',' + 1 实例之后提前一个 temp char *

于 2010-12-21T21:21:55.740 回答
1

假设您想要 {234,23,34,45}。

使用 strchr

#include <string.h>

void print_nums(char *s)
{
    char *p;

    for (p = s; p != NULL; p = strchr(p, ','), p = (p == NULL)? NULL: p+1) {
        int i = atoi(p);
        printf("%d\n", i);   /* or whatever you want to do with each number */
    }
}

或者更容易阅读:

void print_nums(char *s)
{
    char *p = s;            /* p always points to the first character of a number */

    while (1) {
        int i = atoi(p);
        printf("%d\n", i);  /* or whatever you want to do with each number */

        p = strchr(p, ','); /* find the next comma */
        if (p == NULL)
            break;  /* no more commas, end of string */
        else
            p++;    /* skip over the comma */
    }
}

使用 strtok

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void print_nums(const char *str)
{
    char *tempstr = strdup(str);
    char *p = NULL;
    const char *delim = ",";

    for (p = strtok(tempstr, delim); p != NULL; p = strtok(NULL, delim)) {
        int i = atoi(p);
        printf("%d\n", i);  /* or whatever you want to do with each number */
    }

    if (tempstr != NULL) {
        free(tempstr);
        tempstr = NULL;
    }
}
于 2010-12-21T21:45:08.203 回答
0

您可以解析字符串并将其拆分为“,”,然后将范围传递给 atoi()。

于 2010-12-21T21:20:55.050 回答
0

为什么不先规范化字符串?

这是一个(未经测试的)功能来做到这一点。

#include <ctype.h>
#include <string.h>

/*
 * remove non-digits from a string
 *
 * caller must free returned string
 */
char *normalize(char *s)
{
    int i, j, l;
    char *t;
    l = strlen(s);
    t = malloc(l+1);
    for (i = 0, j = 0; i < l; i++) {
        if (isdigit(s[i]))
            t[j++] = s[i];
    }
    t[j] = '\0';
    return t;
}

然后代替

int intvalue = atoi(numstring);

做这个

char *normalized = normalize(numstring);
int intvalue = atoi(normalized);
于 2010-12-21T21:25:05.850 回答
0
int my_atoi(const char * str) {

  if (!str)
    return 0; // or any other value you want

  int str_len = strlen(str);
  char *num_str = (char *)malloc(str_len * sizeof(char));

  int index = 0;
  for (int i = 0; i < str_len; ++i) {
    char ch = str[i];

    if (ch == 0) {
      num_str[index] = 0;
      break;
    }

    if (isdigit(ch))
      num_str[index++] = ch;
  }
  num_str[index] = 0;

  int ret = atoi((const char *)num_str);
  free(num_str);
  return ret;
}

然后调用my_atoi(const char *)函数:

char *str = "234,23";
int v = my_atoi(str);
于 2010-12-21T21:43:11.113 回答