Modify a char* string in C

前端 未结 6 1274
既然无缘
既然无缘 2021-01-27 23:32

I have this:

char* original = \"html content\";

And want to insert a new

char* mycontent = \"newhtmlinsert\";

6条回答
  •  春和景丽
    2021-01-27 23:56

    The string.h function strcat will concatenate two strings, however it will fail when there is not enough space for the new string. My solution is to make your own version of strcat:

    char* myStrCat(const char* str1, const char* str2)
    {
        char* result;
        char* itr1;
        char* itr2;
    
        if (str1 == NULL || str2 == NULL)
        {
            return NULL;
        }
    
        result = (char*)malloc(sizeof(char) * (strlen(str1) + strlen(str2) + 1));   
    
        itr1 = result;
        itr2 = (char*)str1;
    
        while (*itr2 != '\0')
        {
            *itr1 = *itr2;
            itr1++;
            itr2++;
        }
    
        itr2 = (char*)str2;
    
        while (*itr2 != '\0')
        {
            *itr1 = *itr2;
            itr1++;
            itr2++;
        }
    
        *itr1 = '\0';
    
        return result;
    }
    

    This is kinda ugly, but it gets the job done :)

提交回复
热议问题