Rews Prog
Rews Prog

Reputation: 51

how to truncate first few characters char array c++

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

Upvotes: 0

Views: 1722

Answers (4)

AngeloDM
AngeloDM

Reputation: 417

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

Upvotes: 0

Mark Toller
Mark Toller

Reputation: 106

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.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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

Upvotes: 1

igon
igon

Reputation: 3046

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.

Upvotes: 0

Related Questions