4

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);
jgauffin
  • 99,844
  • 45
  • 235
  • 372
user2537446
  • 43
  • 1
  • 1
  • 3

5 Answers5

15

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

VoidPointer
  • 3,037
  • 21
  • 25
2

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

Cameron
  • 96,106
  • 25
  • 196
  • 225
1

C doesn't have good string support. Instead you use "C strings", which are just character arrays. You can do what you want using C strings and the printf function:

const char * second = "sec";
const char * fourth = "four";
printf("First string %s Third %s\n", second, forth);
DaoWen
  • 32,589
  • 6
  • 74
  • 101
0
#include<stdio.h>  
#include<string.h>   

int main(void)  
{  
  char buff[20];  
  char one[] = "one";  
  char two[] = "two";  
  char three[] = "three";  
  char four[] = "four";  
  memset(buff,'0',sizeof(buff));  

  //strcat(buff,(strcat(one,(strcat(two,(strcat(three,four)))))));  
  ////Why the above doesnt work???  ////
  strcat(two,three);  
  strcat(one,two);  
  strcat(buff,one);  
  puts(buff);    
  return 0;  
}  
0

I'm new to the C language and Loadrunner.

Stop. Do not pass GO. Do not collect your consulting fees. Learn C.

Having expertise in the language of your test tool is a foundation skill required to master before picking up the tool to use it in anger. The same holds with Jmeter and Java, SilkPerformer and Pascal, etc...

You will have a large enough learning curve with LoadRunner that you do not need to be brushing up on a core foundation skill at the same time, especially so if you have not been through formal training on tools and process and you have not been assigned to be a part of an internship for a period of time, as much as a year in some cases.

James Pulley
  • 5,606
  • 1
  • 14
  • 14