blob: 036a564f24a45d243c6ee87c0d347732c41e265d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
#include <iostream>
#include <cstring>
#pragma warning (disable:4996)
using namespace std;
const unsigned CAPACITY = 1024;
bool isPrefix(const char* text, const char* prefix)
{
int i = 0;
while (prefix[i] != '\0')
{
if (text[i] == '\0' || text[i] != prefix[i])
return false;
i++;
}
return true;
}
//допускаме, че в text има достатъчно място.
void stringReplace(char* text, const char* pattern, char* replace)
{
char newText[CAPACITY]; //extra space
unsigned newTextIter = 0;
char* textIter = text;
unsigned replacedSize = strlen(replace);
unsigned patternSize = strlen(pattern);
while (*textIter != '\0')
{
if (isPrefix(textIter, pattern))
{
newText[newTextIter] = '\0'; //so strcat would work
strcat(newText, replace);
newTextIter += replacedSize;
textIter += patternSize;
}
else
{
newText[newTextIter++] = *textIter;
textIter++;
}
}
newText[newTextIter] = '\0';
strcpy(text, newText);
}
int main()
{
char text[CAPACITY] = "I am the best of the best!";
char pattern[] = "best";
char replace[] = "worst";
stringReplace(text, pattern, replace);
cout << text << endl;
}
|