Sunday
Nov252012
C - Remove/Replace Characters in a String
Sunday, November 25, 2012 at 8:54PM
When I needed to remove/replace characters in a string, I posted a question here on stackoverflow.
I have used the strstr function in a loop, but was looking for a simpler solution. A C implementation equivalent to the C# String.Replace method might work.
Problem
- Given a string (example : captured by LoadRunner's web_reg_save_param).
- Replace all the & character sequences with the & character.
Solution #1
Simple Solution
char strSource[] = "/url/i.jsp?id=10002&c=10008&p=AC&v=2&s=3&m=1"; char strTemp[1024]; char *s = (char*)strSource; int i=0; while (*s) { strTemp[i++] = *s; if (strncmp(s,"&",5) == 0) { s += 5; } else s++; } strTemp[i] = 0; // strTemp = /url/i.jsp?id=10002&c=10008&p=AC&v=2&s=3&m=1
This works for this specific problem, but what if we want to be more flexible?
Solution #2
- Create a reusable function.
- Pass the source, from and to strings as parameters to the function.
- Dynamically determine the length of the strings.
- Save the resulting string into a LoadRunner parameter.
Flexible Solution
void solution2 (char *strSource, char *strFrom, char *strTo, char *strParam) { char strTemp[1024]; char *s = (char*)strSource; int i=0; int iLenFrom = strlen (strFrom); int iLenTo = strlen (strTo ); while (*s) { if (strncmp (s, strFrom, iLenFrom) == 0) { strncpy (&(strTemp[i]), strTo, iLenTo); i += iLenTo; s += iLenFrom; } else { strTemp[i++] = *s; s++; } } strTemp[i] = 0; lr_save_string (strTemp, strParam); } Action() { char strSource[] = "/url/i.jsp?id=10002&c=10008&p=AC&v=2&s=3&m=1"; lr_save_string (strSource, "pNewValue0"); solution_2 (strSource, "&", "&", "pNewValue1"); solution_2 (strSource, "&", "[AAA]", "pNewValue2"); solution_2 (strSource, "&aaamp;", "[BBB]", "pNewValue3"); solution_2 (strSource, "&", "", "pNewValue4"); solution_2 (strSource, "00", "[X]", "pNewValue5"); // Parameters created // pNewValue0 = /url/i.jsp?id=10002&c=10008&p=AC&v=2&s=3&m=1 // pNewValue1 = /url/i.jsp?id=10002&c=10008&p=AC&v=2&s=3&m=1 // pNewValue2 = /url/i.jsp?id=10002[AAA]c=10008[AAA]p=AC[AAA]v=2[AAA]s=3[AAA]m=1 // pNewValue3 = /url/i.jsp?id=10002&c=10008&p=AC&v=2&s=3&m=1 // pNewValue4 = /url/i.jsp?id=10002c=10008p=ACv=2s=3m=1 // pNewValue5 = /url/i.jsp?id=1[X]02&c=1[X]08&p=AC&v=2&s=3&m=1 return 0; }
Moving Forward
- Dynamically allocate the strTemp variable.
- Error checking for empty strings and chars not found.
- Replace strncmp/strncpy with memcmp/memcpy.
Reader Comments