gpt4 book ai didi

C - 子字符串(从 POS 到 POS)

转载 作者:行者123 更新时间:2023-11-30 15:59:39 26 4
gpt4 key购买 nike

我有一个长度为 32 的字符数组,想从中取出某些字符。例如

111111000000000000000000111111 <32 个字符

我想采用字符 0-6,即 111111

或者甚至采用字符 26-31,即 111111

char check_type[32];

以上是我的声明方式。

我希望能够做的是定义一个函数或使用一个占据起始位置和结束字符的函数。

我研究了很多方法,例如使用 strncpystrcpy 但还没有找到方法。

最佳答案

我会简单地包装strncpy:

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

/* Creates a sub-string of range [start, end], return value must be freed */
char *substr(char *src, size_t start, size_t end)
{
size_t sub_len = end - start + 1;
char * new_str = malloc(sub_len + 1); /* TODO: check malloc's return value */

strncpy(new_str, src, sub_len);
new_str[sub_len] = '\0'; /* new_str is of size sub_len + 1 */

return new_str;
}

int main(void)
{
char str[] = "111111000000000000000000111111";
char *sub_str = substr(str, 0, 5);

puts(sub_str);

free(sub_str);
return EXIT_SUCCESS;
}

输出:

111111

关于C - 子字符串(从 POS 到 POS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com