读书人

字符串插入有关问题

发布时间: 2012-09-17 12:06:51 作者: rapoo

字符串插入问题
怎样实现
char *p = "hello world!";
"hello world!"在文字常量区,不能直接修改
要求
在堆区操作
将no插入ll之间
写一个新的函数完成功能
函数原型void myCopy();//只能有两个形式参数

int main(void)
{
char *p = "hello world!";
char *tp = "no";

myCopy( ...,... );

printf("%s",p);
return 0;
}//大牛们帮帮忙吧,谢谢


[解决办法]

C/C++ code
#include <stdio.h>#include <string.h>#include <stdlib.h>char * myCopy(char * source, const char *str, const char pos){    int i= 0;    int flag = 0;    int len = strlen(str);    int j = 0;    int k = 0;    char * temp = (char *)malloc(strlen(source) + strlen(str));    for(i = 0; i<(int)strlen(source); i++)    {        temp[k] = source[i];        if(source[i] == pos && flag == 0)        {            flag = 1;            for(j = 0;j<len;j++)            {                temp[k + 1] = str[j];                k++;            }        }        k++;    }    return temp;}int main(){    char * p = "hello world";    const char * str = "no";    const char pos = 'l';    printf("before insert:%s\n", p);    printf("after insert:%s\n", myCopy(p, str, pos));    exit(EXIT_SUCCESS);} 

读书人网 >C语言

热点推荐