James Diaz
James Diaz

Reputation: 329

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

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.

Upvotes: 4

Views: 43608

Answers (5)

Sahil Goyal
Sahil Goyal

Reputation: 35

you could use strtok with "," as a delimiter to separate the parts of the second string and then use strcat to append that part onto the first string

Upvotes: 1

Axel
Axel

Reputation: 14159

If you really want to, use strcat (if you don't use strings, you should be ok with the C-functions anyway):

const char * first_string = "Every morning I";
const char * second_string = "go to the library, eat breakfast, swim.";
char final_string[80]; // make sure it's big enough - I haven't counted ;-)

strcpy(final_string, first_string);     // copy to destination
strcat(final_string, second_string+18); // append part of the second string

Upvotes: 4

Guarita
Guarita

Reputation: 163

I'd use 'strncat()' like this:

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

char final_string [200];

//Copies first string first
strcpy(final_string, first_string);

//Copies second string
strncat(final_string, second_string[ text_position ], text_length);

Replace text_position with the position of second_string from which you may want to start copying text and replace text_length with the length of the portion of text you want to copy.

This way you may copy separate portions of text and not necessarily from a point of the string to the end.

Upvotes: 1

Innkeeper
Innkeeper

Reputation: 673

You can use strstr() to search for the begining of the part you want, then strcat() to concatenate.

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

char* s = "eat";
char* r = strstr(second_string, s);

strcat(final_string, first_string);
strcat(final_string, " ");
strcat(final_string, r);

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258608

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.

Upvotes: 7

Related Questions