C 从字符串的一部分获取数值

标签 c string int long-integer strtol

我的任务是从 char[] 的一部分获取 long 数值,其中我有其开始和结束的索引。我刚刚学习 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]}    
}

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

最佳答案

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

好的,所以逻辑应该是

  1. 根据 end-start+1 索引范围创建一个 char 数组。
  2. 做一个memcpy()从源到新数组的end-start大小。
  3. 以空值终止数组。
  4. 使用strtol()数组转换为数值。

关于C 从字符串的一部分获取数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30458067/

相关文章:

c - 从文件填充 Gtk 树存储

c - 使用两个数组作为素数

复制从文件中读取的字符串并将其存储在二维字符串数组中

string - 如何从数字列表中获取字符串?

android - 使用共享首选项存储 int 值

c - 在静态库中查找静态分配的数据 block

c# - 在 C# 中使用 for 循环创建查询字符串

Java String.replace() 或 StringBuilder.replace()

java - 是否可以为 Int 数组中的所有数字赋值?

java不打印任何内容而不是0