数据结构示例之插入子字符串

来源:互联网 发布:mysql mvcc 乐观锁 编辑:程序博客网 时间:2024/05/16 17:15

以下为“插入子字符串”的简单示例:

1. 用c语言实现的版本

#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX_SIZE 100/* 在指定位置后插入字符串 */void insert (char *desStr, char *insertStr, int pos){char string[MAX_SIZE], *temp =string;int desStrLength = strlen(desStr);if ( pos < 0 || pos > desStrLength )    {printf ( "插入位置不正确!\n");exit (1);}if (!desStrLength) //源字符串为空字符串{strcpy (desStr,  insertStr);}else if (desStrLength) //源字符串为非空字符串{strncpy(temp, desStr, pos); //复制源字符串中前pos个字符串strcat(temp, insertStr) ; //追加要插入的字符串strcat(temp, (desStr + pos)); //复制源字符串中pos位置之后的字符串strcpy(desStr, temp);}}void main (){char desStr[MAX_SIZE] = "Sitplease.";char insertStr[MAX_SIZE] = " down ";/* 在指定位置后插入字符串 */insert(desStr, insertStr, 3);printf("原始字符串:%s\n", desStr);printf("要插入的字符串:%s\n", desStr);printf("操作结果:%s", desStr);printf ( "\n");}
运行结果如下所示:



0 0