Please see my updated version below. *20121103 Update.Thanks :)*
I am currently reading The C Programming Language by Dennis Richie and Brian Kernighan, and I came to implement the function squeeze (s1, s2) as an exercise. squeeze() deletes each character in s1 that matches any character in the string s2. While coding squeeze(), I thought that I can extend its capability to act like trim() method in Java, and then the my code was already done, and tested.
However, even though it is implemented in C, I believe that the code below can be improved and optimized. Please help me do so.
char *squeeze (char *str1, char *str2) {
int i, j;
int str1Len = strlen (str1);
int toBeSubtractLen = 0;
char chr1 = '\0';
char chr2 = '\0';
for (i = 0; i < str1Len; i++) {
chr1 = str1 [i];
for (j = 0; j < strlen (str2); j++) {
chr2 = str2 [j];
if (chr1 == chr2) {
toBeSubtractLen++;
}
}
}
char *finalStr;
finalStr = malloc ((str1Len - toBeSubtractLen) + 1);
if (finalStr == NULL) {
printf ("Unable to allocate memory.\n");
exit (EXIT_FAILURE);
}
int indx = 0;
for (i = 0; i < str1Len; i++) {
chr1 = str1 [i];
for (j = 0; j < strlen (str2); j++) {
chr2 = str2 [j];
if (chr1 == chr2) {
break;
}
}
if (chr1 != chr2) {
finalStr[indx] = chr1;
indx++;
}
}
return finalStr;
} /* end of squeeze() */
Samples:
- str1 = ",AaBbCcDdEeFfGgHhIiJjKkLlMmAaAaAaNnOoPpQqRrSsTtUuVvWwXxYyZz"
- str2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- str3 = "abcdefghijklmnopqrstuvwxyz"
- name = "ChristopherM.Sawi"
- birthday = "August14,1988"
Outputs:
- squeeze-ing str1 by str2 yields: ",abcdefghijklmaaanopqrstuvwxyz"
- squeeze-ing str1 by str3 yields: "mABCDEFGHIJKLMAAANOPQRSTUVWXYZ"
- squeeze-ing str2 by str3 yields: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- squeeze-ing name by str3 yields: "CM.S"
- squeeze-ing birthday by str1 yields: "141988"
20121103 Update: I have already implemented some of you recommendations before. I also improved my code by using pointers. However, what is wrong with address incrementation part below *squeezed_str++*? It seems that address is not incrementing.
PS. substring() function is working. :)
char *squeeze (char *str, int start_index, int end_index, char *ref_str) {
char *substr;
substr = malloc (sizeof (*substr));
if (substr == NULL) {
printf ("Unable to allocate memory.\n");
exit (EXIT_FAILURE);
}
char *squeezed_str;
squeezed_str = malloc (sizeof (*squeezed_str));
if (squeezed_str == NULL) {
printf ("Unable to allocate memory!\n");
exit (EXIT_FAILURE);
}
substr = substring (str, start_index, end_index);
int substr_len = strlen (substr);
int refstr_len = strlen (ref_str);
char chr1, chr2; chr1 = chr2 = '\0';
for (int i = 0; i < substr_len; i++) {
chr1 = *(substr+i);
for (int j = 0; j < refstr_len; j++) {
chr2 = *(ref_str + j);
if (chr1 == chr2) {
break;
}
}
if (chr1 != chr2) {
*squeezed_str = *(substr+i);
squeezed_str++;
}
}
return squeezed_str;
} /* end of squeeze() */