Inserting characters in the middle of char array

后端 未结 5 1183
南方客
南方客 2021-01-23 03:51

I have a char array filled with some characters. Let\'s say I have \"HelloWorld\" in my char array. (not string. taking up index of 0 to 9)

What I\'m trying to do is ins

相关标签:
5条回答
  • 2021-01-23 04:27

    The initial starting value for the inner loop is one short. It should be something like the following. Note too that since the characters are moved to the right, a new null terminator needs to be added:

        ch[strlen(ch) + 1] = '\0';
        for(j=strlen(ch); j>=i+2; j--) {  // note no "-1" after the strlen
    

    Edit As far as the "Is this a good way?" part, I think it is reasonable; it just depends on the intended purpose. A couple thoughts come to mind:

    • Reducing the calls to strlen might be good. It could depend on how good the optimizer is (perhaps some might be optimized out). But each call to strlen require a scan of the string looking for the null terminator. In high traffic code, that can add up. So storing the initial length in a variable and then using the variable elsewhere could help.
    • This type of operation has the chance for buffer overflow. Always make sure the buffer is long enough (it is in the OP).
    0 讨论(0)
  • 2021-01-23 04:28

    If you want to move all the characters up by one, then you could do it using memmove.

    #include <string.h>
    
    char ch[15];
    
    int make_room_at = 5;
    int room_to_make = 1;
    
    memmove(
        ch + make_room_at + room_to_make,
        ch + make_room_at,
        15 - (make_room_at + room_to_make)
    );
    
    0 讨论(0)
  • 2021-01-23 04:30

    If you're going to manipulate a char array you shouldn't make it static. By doing this:

    char ch[15];
    

    you're hardcoding the array to always have 15 characters in it. Making it a pointer would be step 1:

    char* ch;
    

    This way you can modify it as need be.

    0 讨论(0)
  • 2021-01-23 04:38

    Simply do:

    #define SHIFT  1
    char bla[32] = "HelloWorld";    // We reserve enough room for this example  
    char *ptr = bla + 5;            // pointer to "World"    
    memmove(ptr + SHIFT, ptr, strlen(ptr) + 1);  // +1 for the trailing null
    
    0 讨论(0)
  • You need to start the inner loop from strlen(ch) + 1, not strlen(ch) - 1, because you need to move the NULL-terminator to the right one place as well. Remember that strlen returns the length of the string such that string[strlen(string)] == '\0'; you can think of strlen as a function for obtaining the index of the NULL-terminator of a C-string.

    0 讨论(0)
提交回复
热议问题