您的位置:首页 > 理论基础 > 数据结构算法

数据结构基础_插入字符串

2013-04-13 10:09 169 查看
源代码

/*
* strcat2.c
*
*  Created on: 2013-4-13
*      Author: yeahwell
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 100

/**
* 把src字符串插入到dest字符串的第position个位置
* @param dest  目标串
* @param src   源串
* @param position 所要插入的位置
*/
void strcat2(char *dest, char *src, int position);

int main(){
char string1[MAX_SIZE] = "amobile", *dest = string1;
char string2[MAX_SIZE] = "uto", *src = string2;
int position = 1;
strcat2(dest, src, position);
printf("连接后的字符串为%s", dest);
return 0;
}

void strcat2(char *dest, char *src, int position){
char string3[MAX_SIZE], *temp = string3;
if(position < 0 || position > strlen(dest)){
fprintf(stderr, "所要插入的位置溢出边界");
exit(EXIT_FAILURE);
}
if(!strlen(dest)){   //如果目标串的长度为0,则直接copy源字符窜
strcpy(dest, src);
}else if(strlen(src)){   //
strncpy(temp, dest, position); //复制dest的前position个字符到temp中
strcat(temp, src);             //连接temp和src
strcat(temp, (dest + position));  //连接dest的position位置之后的字串
strcpy(dest, temp);           //复制temp字符窜到dest中
}

}


运行结果:

连接后的字符串为automobile
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐