-2

我的任务是从 的一部分中获取long数值char[],其中我有它的开始和结束的索引。我只是在学习 C,所以我很困惑哪个函数在我的情况下效果最好..

可以说我正在制作功能getNum()

static char words[100000]; //lets say this is string filled  with many num. values and other stuff.  

long getNum(int begin, int end){
 return (long){part of string starting at words[begin] and ending at words[end]}    
}

我想知道最好的方法和最简单的方法来做到这一点。任何其他评论也非常感谢。

4

2 回答 2

0

我们给算法,你写代码。同意?

好的,所以逻辑应该是

  1. char根据end-start+1索引范围创建一个 s 数组。
  2. 做一个memcpy()从源到新数组的end-start大小。
  3. 空终止数组。
  4. 用于strtol()数组转换为数值。
于 2015-05-26T12:09:04.363 回答
0

我意识到我不需要数值结尾的索引。

到目前为止,以下解决方案似乎是最简单的:

static char words[100000]; //lets say this is string filled  with many num. values and other stuff.  
static char *endp;

long getNum(int begin){
 return strtol(&words[begin], &endp, 10);    
}

Sourav Ghosh 的上述解决方案包括使用结束索引

于 2015-05-26T13:54:47.677 回答