Vugen: Replace Any String With Another
Posted on Jul, 2012 by Admin
Here is an easy way to replace anything with anything in a captured string in your LoadRunner Vugen script. It is a function called “string_replace”. Place this in the top of your action section, right after the include but before the main section begins:
char *string_replace(char *input_string,
char *substring_to_be_replaced,
char *substitution_string)
{
// strstr function declaration
char *strstr(const char *s1, const char *s2);
// newstring variable the new string to be returned
// increase the buffer size if needed. Default is 200
char newstring[200]="";
// str is a temporary pointer to aid in creation of newstring;
// it points at the beginning of each substring that
// needs to be included in the new string.
char *str;
// ptr is a pointer to hold strstr result.
char *ptr;
str = input_string;
// search for substring_to_be_replaced and
// replace with substitution_string
while((ptr = strstr(input_string, substring_to_be_replaced))!=NULL)
{
input_string = &ptr[strlen(substring_to_be_replaced)];
ptr[0] = '\0';
strcat(newstring, str);
strcat(newstring, substitution_string);
str = input_string;
}
// concatenate the rest of the string
strcat(newstring, input_string);
return newstring;
}
Now here is an example of how this might be used. Let’s say you captured a string that had “&” in it and you need to replace them with simply a “&” character. You need to search the string and replace multiple occurrences. This is what it might look like in your action section:
Action1()
{
lr_save_string("Value=RS=&OI=&LI=&BD=20020107&ED=99991231&SQ=0&XXXXX;",
"pInputString");
lr_save_string(string_replace(lr_eval_string("{pInputString}"),
"&",
"&"),
"pNewString");
lr_output_message("newstring: %s", lr_eval_string("{pNewString}"));
return 0;
}
Here is what the output/execution log might look like in Vugen with standard logging turned on:
Running Vuser…
Starting iteration 1.
Starting action Action.
Action.c(34): newstring: Value=RS=&;OI=&;LI=&;BD=20020107&;ED=99991231&;SQ=0&;XXXXX;
Ending action Action.
Ending iteration 1.
Ending Vuser…
Starting action vuser_end.
Ending action vuser_end.
Vuser Terminated.
Notice that this function saves the string as pInputString. This may be changed to dynamically pull a value from a web page with the web_reg_save_param() function too. Also, notice how string_replace() is used to scan, replace, and save the new string by being embedded in the lr_save_string() function. The lr_output_message() is totally optional. Instead you might actually use the {pNewString} parameter in your script where it is needed.