how to truncate first few characters char array c++

1.7k views Asked by At

I have a char array called names[50]

Basically, I use

strncpy(this->names, names, sizeof(names))

however this will only truncate characters at the end.

How do I truncate characters from the start?

For example, BillSteveLinusMikeGeorgeBillSteveLinusMikeGeorgeGeorge should be teveLinusMikeGeorgeBillSteveLinusMikeGeorgeGeorge

4

There are 4 answers

0
igon On

You can change the source address for strncpy:

strncpy(this->names, &(names[10]), num_of_chars_to_copy);

Notice that no null-character is implicitly appended at the end of the destination string if the source string is longer than num.

2
Vlad from Moscow On

If I have understood correctly then using the string you showed as an example you have to write

strncpy( this->names, names + 5, sizeof(names) - 5 );
0
Mark Toller On

You need to be clear what you want to do... is names[] variable in length from call to call? Is this->names a fixed length? Note that the length for the number of bytes to copy should be the number of bytes available in this->names... Otherwise you run the risk of overflowing the memory.

0
AngeloDM On

I designed for you this simple function, You can use it as reference code for more complex issue:

void BackStrCopy(char* src, char* dest, int srcsize, int destsize)
{
    if(srcsize >= destsize )
    {
        do
            dest[destsize--] = src[srcsize--];
        while( destsize + 1 );
    }
}

int main()
{
  char* src    = "BillSteveLinusMikeGeorgeBillSteveLinusMikeGeorgeGeorge";
  char  dest[50];
  BackStrCopy(src, dest, strlen(src), 25);
}

I tested it end work.

I thing that the function code does not require any comment:) If my solution help you, please remember to check it as answered.

Ciao