从* char解析int的快速简便方法

时间:2017-09-21 06:10:41

标签: c string parsing numbers

我有以下字符串

char *filename = "/home/data/slice-10-1.dat";

我需要解析以下内容

int sliceTime
int sliceIndex;

sliceTime应为10,sliceOrder应为1

2 个答案:

答案 0 :(得分:4)

像这样使用strtok()atoi()

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

int main (void)
{
  char str[] = "/home/data/slice-10-1.dat";
  int sliceTime, sliceIndex, counter = 0;
  char * pch;
  pch = strtok (str," ./-");
  while (pch != NULL)
  {
    //printf("%s\n" ,pch);
    size_t ln = strlen(pch) - 1;
    if( pch[ln] == '\n' ) pch[ln] = '\0';
    int notNumber = 0;
    /* Ensure that input is a number */
    for(size_t i = 0; i < ln; i++) {
      if( !isdigit(pch[i]) ) {
        notNumber = 1;
      }
    }
    if(!notNumber)
        if(counter++ == 0)
            sliceTime = atoi(pch);
        else
            sliceIndex = atoi(pch);
    pch = strtok (NULL, " ./-");
  }
  printf("SliceTime = %d, SliceIndex = %d\n", sliceTime, sliceIndex);
  return 0;
}

输出:

  

SliceTime = 10,SliceIndex = 1

如果您始终使用相同的字符串模式,请使用BLUEPIXY的解决方案,使用sscanf()

#include <stdio.h>

int main(void) {
    char *filename = "/home/data/slice-10-1.dat";
    int sliceTime, sliceIndex;
    if(sscanf(filename, "%*[^-]-%d-%d", &sliceTime, &sliceIndex) == 2){
        printf("%d, %d\n", sliceTime, sliceIndex);
    }
    return 0;
}

输出:

  

10,1

答案 1 :(得分:1)

使用strtok()获取令牌,然后使用atoi()将字符串转换为整数。

相关问题