gpt4 book ai didi

c - 向数组中插入一个值,并根据值c排列数组

转载 作者:行者123 更新时间:2023-11-30 17:10:37 25 4
gpt4 key购买 nike

char num = '5';
strcpy(array, "2,3,7,9")

大家好,如果想根据结果将 5 插入数组,有什么想法吗?我该怎么做?

数组=“2,3,5,7,9”

最佳答案

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

void insert_string(char *target, const char *to_insert, int index) {
int count = 0;
int i;
int move_dst;
int insert_comma = 0;
int to_len = strlen(to_insert);
if (index < 0) index = 0;
if (index <= 0) {
i = 0;
} else {
for (i = 0; target[i] != '\0'; i++) {
if (target[i] == ',') {
count++;
if (count >= index) {
i++;
break;
}
}
}
}
/* i is where to insert the string */
if (target[i] == '\0') {
/* the insertion target was end of the string */
target[i] = ',';
target[++i] = '\0';
}
move_dst = i + to_len;
if (target[i] != '\0') {
/* the sequence continues after insertion point */
move_dst++;
insert_comma = 1;
}
memmove(&target[move_dst], &target[i], strlen(&target[i]) + 1); /* copy includes termination '\0' */
memcpy(&target[i], to_insert, to_len);
if (insert_comma) target[i + to_len] = ',';
}

int main(void) {
char array[1024];
char num = '5';
char num_string[2] = {num, '\0'};
int c = 2;
strcpy(array, "2,3,7,9");
puts(array);
insert_string(array, num_string, c);
puts(array);
return 0;
}

关于c - 向数组中插入一个值,并根据值c排列数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809394/

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