首页 > 其他 > 详细

字符串插入

时间:2019-08-10 18:58:31      阅读:103      评论:0      收藏:0      [点我收藏+]
//将某个字符串插入到一个字符串中,在hello cpp hello china中,在cpp后插入luoxu
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * insertString(char *str, char *substr, char *source){
    if (str == NULL || substr == NULL){
        return NULL;
    }
    else{
        char *newStr = (char *)calloc(strlen(str)+strlen(source)+1, sizeof(char));
        char *p = strstr(str, substr);
        char *tmp;
        strcpy(tmp,p+3);
        *(p+3) =\0;
        strcat(newStr,str);
        strcat(newStr, source);
        strcat(newStr,tmp);

/*        char *strEnd = str + strlen(str);
        char *newStrEnd = newStr + strlen(newStr);
        do{
            *newStrEnd = *strEnd;
            newStrEnd++;
            strEnd++;
        } while (pAt == strEnd);
        while (pAt != strstr(newStr, substr)){
            *pAt = *substr;
        }*/
        return newStr;


    }

}
//指针方式实现    //没有实现成功
void main(){
    char *str = "hello cpp hello china";
    char *p = insertString(str, "cpp","luoxu");
    printf("%s\n", p);
    system("pause");
}

void main11(){
    char str1[50] = "hello cpp hello china";
    char str2[10] = "cpp";
    char str3[10] = "luoxu";
    char *p = strstr(str1,str2);
    char tmp[20];
    strcpy(tmp,p+3);
    *(p+3) = \0;
    strcat(str1, str3);
    strcat(str1, tmp);
    printf("%s\n", str1);
    system("pause");
}

 

字符串插入

原文:https://www.cnblogs.com/luoxuw/p/11332331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!