Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple string concatenation [duplicate]

Tags:

c

cstring

I'm new to the C language and Loadrunner.

How do I do a string concatenation in C.

Pseudo code:

String second = "sec";
String fouth = "four";
System.out.println("First string" + second +"Third" + fouth);
like image 460
user2537446 Avatar asked Dec 03 '22 22:12

user2537446


2 Answers

If you are sure that target string can accommodate, you can use snprintf,

#define SIZE 1024

char target[ SIZE ];
// .. ..
snprintf( target, sizeof( target ), "%s%s%s", str1, str2, str3 );

For your case,

snprintf( target, sizeof( target ), "%s%s%s%s", "First string", second, "Third", fourth );

Of course, second and fourth should be valid string (character array).

like image 142
VoidPointer Avatar answered Dec 20 '22 11:12

VoidPointer


Well, to start with C isn't object-oriented -- there's no "String" type, only pointers to arrays of characters in memory.

You can accomplish concatenation using the standard strcat call:

char result[100];    // Make sure you have enough space (don't forget the null)
char second[] = "sec";    // Array initialisation in disguise
char fourth[] = "four";

strcpy(result, "First string ");
strcat(result, second);
strcat(result, "Third ");
strcat(result, fourth);

printf("%s", result);

But it won't be very efficient because strcat has to walk every character in both the source and destination strings in order to find out how long they are (a null byte is placed at the end of the string to act as a terminal/sentinel).

like image 38
Cameron Avatar answered Dec 20 '22 13:12

Cameron