Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- // Задача 7. Дефинирайте стринг „I am a poor programmer”. Заменете през пойнтер “poor” с “great”.
- char *replaceWord(const char *s, const char *pcOldWord, const char *pcNewWord)
- {
- char *pcResult;
- int i, iCounter = 0;
- int iNewWordLength = strlen(pcNewWord);
- int iOldWordLength = strlen(pcOldWord);
- for (i = 0; s[i] != '\0'; i++)
- {
- if (strstr(&s[i], pcOldWord) == &s[i])
- {
- iCounter++;
- i += iOldWordLength - 1;
- }
- }
- pcResult = (char *)malloc(i + iCounter * (iNewWordLength - iOldWordLength) + 1);
- i = 0;
- while (*s)
- {
- if (strstr(s, pcOldWord) == s)
- {
- strcpy(&pcResult[i], pcNewWord);
- i += iNewWordLength;
- s += iOldWordLength;
- }
- else
- pcResult[i++] = *s++;
- }
- pcResult[i] = '\0';
- return pcResult;
- }
- int main()
- {
- char str[] = "I am a poor programmer";
- char c[] = "poor";
- char d[] = "good";
- char *result = NULL;
- printf("Old string: %s\n", str);
- result = replaceWord(str, c, d);
- printf("New String: %s\n", result);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement