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

标签 c arrays

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/

相关文章:

c - 在 C 中为矩阵分配内存,为什么我之后不能访问矩阵?

javascript - 无法正确获取4个数组之间的公共(public)元素

javascript - Highcharts 使用数组显示每个气泡点的附加信息

javascript - 在javascript中添加多个元素

java - 从 String 创建 int[] 数组(仅限正整数)

C-如何将文本文件中的单词读入字符串数组

c - 如何创建一个函数,如果数字是质数,则返回 1,如果不是质数,则在 C 编程中返回 0

c - 以相反的顺序读取文件行(结构、成员、malloc)

C++ Win32——COM 方法 : equivalent C declaration

在 C 中创建结构体数组