Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ copy a part of a char array to another char array

Tags:

c++

I'm trying to copy only a portion of a string (or char *) into another string (or another char *)

char * first_string = "Every morning I"
char * second_string = "go to the library, eat breakfast, swim."
char * final_string;

I would like to copy part of the second_string into the first_string.

For Example:

Every morning I eat breakfast.

What is the function that allows you to copy only a portion of a string, starting from a specific point in the string?

Note: I don't want to use string variables, but char *, or even char arrays, if possible.

like image 464
James Diaz Avatar asked Dec 12 '22 20:12

James Diaz


1 Answers

It's std::copy, but with your code it would result in undefined behavior, because you have pointers to string literals, which are illegal to modify.

You'll need something like

char first_string[256] = "Every morning I";
char second_string[256] = "go to the library, eat breakfast, swim.";

std::copy(
    &second_string[23],
    &second_string[36],
    &first_string[strlen(first_string)]
);

Indices might be off.

like image 199
Luchian Grigore Avatar answered Feb 06 '23 06:02

Luchian Grigore