C语言--工具函数(一)--字符数组中插入字符串

一、指定位置插入一个字符

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100

char query[] = "insert into babyData values(,'yuanlifu',37.5,0,22,0,55,0,10,0,12,0,23,0,now());";

void insert(char *str, char *pch, int pos) {
	int len = strlen(str);
	for (int i = len - 1; i >= pos; --i) {
		*(str + i + 1) = *(str + i);
	}
	*(str + pos + n) = *pch;
	*(str + len + 1) = 0;
}

int main() {
	char ch = '8';
	puts(query);
	insert(query, &ch, 28);
	puts(query);
	return 0;
}

原版

#include <stdio.h>
#include <string.h>
 
void insert(char *str, char *pch, int pos){
    int l = strlen(str);
    for(int i = l - 1; i >= pos; --i){
        *(str + i + 1) = *(str + i);
    }
    *(str + pos) = *pch;
    *(str + l + 1) = 0;
}
 
int main(){
    char str[100] = "abcdefg";
    char ch = '2';
    puts(str);
    insert(str, &ch, 3);
    puts(str);
    return 0;
}

修改之后(完美)指定位置开始插入多个字符:

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

char query[] = "insert into babyData values(,'yuanlifu',37.5,0,22,0,55,0,10,0,12,0,23,0,now());";

void insert(char *str, char *pch, int pos) {
	int len = strlen(str);
	int nlen = strlen(pch);
	for (int i = len - 1; i >= pos; --i) {
		*(str + i + nlen) = *(str + i);
	}
	for (int n = 0; n < nlen;n++)
	*(str + pos + n) = *pch++;
	*(str + len + nlen) = 0;
}

int main() {
	char ch[] = "4558";
	puts(query);
	insert(query, ch, 28);
	puts(query);
	return 0;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页