How to push char array? [duplicate]

2019-09-21 17:38发布

问题:

Possible Duplicate:
How do I use arrays in C++?

I have no idea how to push a char array.
For example if i have "HI.MY.NAME.IS" in a char array,
I would like to put one char in the middle and push the char's right to it.
So it would be something like "HI.MY.SLAME.IS" or something like that.

Any possible solutions?

回答1:

Use string::insert.

std::string s("test");
s.insert(s.begin()+2, 'c');


回答2:

There is no "automatic" push which relocates elements in an array. At the lowest levels, there is only read from an array element and write to an array element.

That means you need to copy each element after the insert "one index" down the array. Then you need to set the "inserted" value at its inserted index.

Library routines will do this for you without you noticing; however, you should be aware of the underlying mechanism. Otherwise, you might fall under the impression that inserting into arrays at arbitrary indexes is cheap (when it usually isn't).



回答3:

//This allocates new memory that you receive responsibility for freeing after use.
char *push(char *charArray, char *charsToPush, int pushPos) {
    char *thePushed = new char[strlen(charArray) +  strlen(charsToPush) + 1];
    memcpy(thePushed, charArray, pushPos);
    memcpy(thePushed + pushPos, charsToPush, strlen(charsToPush));
    memcpy(thePushed + pushPos + strlen(charsToPush), charArray + pushPos, strlen(charArray) - pushPos);
    thePushed[strlen(charArray) +  strlen(charsToPush)] = '\0';
    return thePushed;
}


回答4:

To do that you'd have to:

  1. Create a new array that is large enough to hold the original and the new items. Arrays cannot be resized.
  2. Copy all items from the old to the new array, leaving the places for the new characters open.
  3. Insert the new characters.

This is quite complex. But C++ offers a simpler way - std::string:

#include <string>
#include <iostream>

int main() {
  std::string text = "HI.MY.NAME.IS";
  std::string new_text = text.substr(0, 6) + "SL" + text.substr(7, 6);
  std::cout << new_text << std::endl;
}

This program prints HI.MY.SLAME.IS. Or, even better, use insert, as @rasmus suggests.



回答5:

If you are limited to c-strings or require it to be replaced in-buffer, then you can do something like the below, but your buffer must be large enough to hold the modified string since it's pushing all characters down. That said, you'd be much better off using the std::string as the others suggest.

// ASSUMES buffer is large enough to store one more char
void insertAt(char* buffer, char insertMe, size_t at)
{
    size_t len = strlen(buffer);

    if (at <= len)
    {
        memcpy(buffer + at + 1, buffer + at, len - at + 1);
        buffer[at] = insertMe;
    }
}


回答6:

char* string = (char*) malloc(14);
string = "HI.MY.NAME.IS";
realloc(string, 15);
for (int i = 14; i > 5; --i) {
    string[i+1] = string[i];
}

string[5] = 'S';
string[6] = 'L';

Here you go...lol