נשלח בתאריך: 08 January 2009 בשעה 17:10 | | IP רשוּם
|
|
|
|
#include <stdio.h> #include <string.h>
#define MAX_LEN 100
/* * This function replaces the occurances of 'sub' in 'src' with the * string 'repl'. * assumption: length of 'repl' smaller or equal to the length of 'sub' */ void str_replace(char *src, char *sub, char *repl) {
char *ptr1, *ptr2; /* two pointers for going over the input string */ int repl_len = strlen(repl), sub_len = strlen(sub); int diff = sub_len - repl_len;
/* loop over all instances of string to replace */ ptr1 = strstr(src, sub); while (ptr1 != NULL) { /* copy replacing string into string. /* we use strncpy in order not to copy the terminator '\0' */ strncpy(ptr1, repl, repl_len);
/* increment both pointers, * ptr1 points to the string after the replacement * ptr2 points to the string after the substituted part * (which may be longer) */ ptr2 = ptr1 + sub_len; ptr1 += repl_len;
/* this loop moves characters backwards, * if the replaced string was shorter than the original part */ while ((*ptr2) != '\0') { *(ptr2-diff) = (*ptr2); ptr2++; } *(ptr2 - diff) = '\0';
/* get next instance */ ptr1 = strstr(ptr1, sub); } }
/* * Read a string from the user until the end of the line. * read no more than size characters and ignore the rest. */ void getline(char *arr, int size) { int counter = 0; char c = getchar();
while (c != '\n') { if (counter < size) { *arr = c; arr++; } counter++; c = getchar(); }
*arr = '\0'; }
int main(int argc, char* argv[]) {
char src[MAX_LEN + 1]; char sub[MAX_LEN + 1]; char repl[MAX_LEN + 1];
printf("Please enter a string: "); getline(src, MAX_LEN); printf("Please enter a part to substitute: "); getline(sub, MAX_LEN); printf("Please enter the replacement: "); getline(repl, MAX_LEN);
/* make sure none of the strings is empty */ if (*src == '\0' || *sub == '\0' || *repl == '\0') { printf("Empty string. Please check your input.\n"); return 1; }
/* make sure the replacment is not longer than the substituted string */ if (strlen(sub) < strlen(repl)) { printf("replacement substring should not be longer than the replaced substring\n"); return 1; }
str_replace(src, sub, repl); printf("after replacement: %s\n", src);getch(); } // End Of File
בהצלחה רבה.
|