FireBirdLib - Topfield TMS PVR TAP Programming Library
StrReplace.c
Go to the documentation of this file.
1#include <string.h>
2#include "libFireBird.h"
3
4bool StrReplace(char *String, const char *Find, const char *Replace)
5{
7
8 int FindLen, ReplaceLen;
9 char *p;
10 bool ret = FALSE;
11
12 //No NULL pointers?
13 if(!String || !Find || !Replace)
14 {
15 TRACEEXIT();
16 return FALSE;
17 }
18
19 //No empty strings? Replace may be empty
20 if(!String[0] || !Find[0])
21 {
22 TRACEEXIT();
23 return FALSE;
24 }
25
26 //At least one match?
27 if(!strstr(String, Find))
28 {
29 TRACEEXIT();
30 return FALSE;
31 }
32
33 FindLen = strlen(Find);
34 ReplaceLen = strlen(Replace);
35 if(FindLen >= ReplaceLen)
36 {
37 //The result won't be larger than the original, so we can directly use the source buffer
38 p = String;
39 do
40 {
41 p = strstr(p, Find);
42 if(p)
43 {
44 ret = TRUE;
45 TAP_MemCpy(p, (void *) Replace, ReplaceLen);
46 strcpy(p + ReplaceLen, p + FindLen);
47 p += ReplaceLen;
48 }
49 } while(p);
50 }
51 else
52 {
53 char *TempBuffer, *s, *d;
54 int NrOfOccurences;
55
56 //Count the number of hits to calculate the buffer size
57 NrOfOccurences = 0;
58 p = String;
59 do
60 {
61 p = strstr(p, Find);
62 if(p)
63 {
64 ret = TRUE;
65 NrOfOccurences++;
66 p += FindLen;
67 }
68 } while(p);
69
70 TempBuffer = TAP_MemAlloc(strlen(String) + NrOfOccurences*(ReplaceLen - FindLen) + 1);
71
72 s = String;
73 p = String;
74 d = TempBuffer;
75 do
76 {
77 p = strstr(p, Find);
78 if(p)
79 {
80 TAP_MemCpy(d, s, p - s);
81 d += (p - s);
82 TAP_MemCpy(d, (void *) Replace, ReplaceLen);
83 d += ReplaceLen;
84
85 p += FindLen;
86 s = p;
87 }
88 } while(p);
89 strcpy(d, s);
90
91 strcpy(String, TempBuffer);
92 TAP_MemFree(TempBuffer);
93 }
94
95 TRACEEXIT();
96 return ret;
97}
bool StrReplace(char *String, const char *Find, const char *Replace)
Definition: StrReplace.c:4
#define TRACEEXIT()
Definition: libFireBird.h:1244
#define TRACEENTER()
Definition: libFireBird.h:1243