【问题标题】:How would you get a string of characters from an array in c? [duplicate]如何从 c 中的数组中获取字符串? [复制]
【发布时间】:2021-04-29 19:38:33
【问题描述】:

我正在尝试解析来自用户的数据。我需要从用户那里得到一个特定的数字。

我并不是说像 strstr()。我的意思更像是数组中的字符 9-12。

例如:

char array[15] = "asdfghjkbruhqw";
                          ^--^

我想不出办法来做到这一点。任何帮助将不胜感激。

【问题讨论】:

  • 这个char数组是不是已经填好了数据?
  • 我不明白你的意思。你需要那个字符串中“bruh”的索引吗?还是需要从9到12中找出字符串的内容是什么?
  • 是的,已经填满了。
  • @altermetax 我需要内容。
  • 那么@vmp 的回答就是你所需要的。

标签: arrays c


【解决方案1】:

C 中的“字符串”的行为与任何其他数组一样,因此为了检索字符串的子集,您必须手动将每个元素从源数组复制到目标数组。有几种方法可以解决这个问题:

最简单的选择

char my_source_array[15] = "asdfghjkbruhqw";
char my_dest_array[5];

int offset_start = 8; /* index of "b" in "bruh" */
int num_chars = 4;

for (int i = 0; i < num_chars+1; ++i) {
  my_dest_array[i] = my_source_array[offset_start+i];
}
my_dest_array[num_chars] = 0; /* don't forget to null-terminate */

稍微高级一点

char my_source_array[15] = "asdfghjkbruhqw";
char my_dest_array[5];

int offset_start = 8; /* index of "b" in "bruh" */
int num_chars = 4; /* number of chars in "bruh" */
memcpy(my_dest_array, my_source_array+offset_start, num_chars*sizeof(char));
my_dest_array[num_chars] = 0; /* don't forget to null-terminate */

【讨论】:

  • 可能想要 nul-terminate my_dest_array,例如my_dest_array[num_chars] = 0; 这样my_dest_array 就可以当作一个字符串来处理了。
【解决方案2】:

使用strcnpcy,在第二个参数中传入起始位置:

char array[15] = "asdfghjkbruhqw";
char dest[10] = "";
strncpy(dest, &arr[9], 3);

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2019-09-06
    • 2015-06-13
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多