Inserting characters in the middle of char array

2019-03-02 16:16发布

问题:

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 insert a character in the middle of the array, and push the rest to the side to make room for the new character that is being inserted.

So, I can make the char array to have "Hello.World" in it.

char ch[15]; // assume it has "HelloWorld" in it
for(int i=0; i<=strlen(ch)-1; i++) {
    if(ch[i]=='o' && ch[i+1]=='W') {
        for(int j=strlen(ch)-1; j>=i+2; j--) {
            ch[j] = ch[j-1]; // pushing process?
        }
        ch[i+1] = '.';
        break;
    }
}

Would this work? Would there be an easier way? I might just be thinking way too complicated on this.

回答1:

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)
);


回答2:

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.



回答3:

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


回答4:

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).


回答5:

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.