我有以下字符串
char *filename = "/home/data/slice-10-1.dat";
我需要解析以下内容
int sliceTime
int sliceIndex;
sliceTime
应为10,sliceOrder
应为1
答案 0 :(得分:4)
#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()
将字符串转换为整数。