Connection characters *

How to connect to char * strings to each other. For instance:

char* a="Heli";
char* b="copter";

How to associate them with one char c, which should be equal to "Helicopter"?

+3
source share
4 answers

strncat

Or use string s.

+8
source
size_t newlen = strlen(a) + strlen(b);
char *r = malloc(newlen + 1);
strcpy(r, a);
strcat(r, b);
+6
source

++:

std::string foo(a);
std::string bar(b);
std::string result = foo+bar;
+3

asprintf() ( ), :

char* p;
int num_chars = asprintf(&p, "%s%s", a, b);

, printf(), , ints, double .., , , .. num_chars!= -1 ( ), p , free(). asprintf() .

++:

std::string result = std::string(a) + b;

: a + b - , , + std::string, , .

(The accepted answer strncatdeserves further comment: it can be used to combine more textual data after the ASCIIZ string in an existing, writable buffer, since there is free space in this buffer. It cannot safely / portable concatenate into a string literal, and it still hurts to create such a buffer . If you do this with the help malloc()to ensure its correct length, then strcat()you can use it, preferring it strncat()anyway.)

+3
source

Source: https://habr.com/ru/post/1791843/


All Articles