字符串插入

//将某个字符串插入到一个字符串中,在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");
}

 

posted @ 2019-08-10 17:27  Coding_Changes_LIfe  阅读(1550)  评论(0编辑  收藏  举报