replace.cpp

(plain text)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <string>
#include <cstring>

void
replace_n (char buf[],
	   std::size_t n,
	   const char dest[], std::size_t dest_len) {
  std::memmove(buf + dest_len, buf + n, std::strlen(buf));
  std::memcpy(buf, dest, dest_len);
}

char *
replace (char buf[],
	 const char src[], std::size_t slen,
	 const char dest[], std::size_t dlen) {
  if (char *p = std::strstr(buf, src)) replace_n(p, slen, dest, dlen);
  return buf;
}

char *
replace (char buf[], const char src[], const char dest[]) {
  return replace(buf, src, std::strlen(src), dest, std::strlen(dest));
}

char *
replaceAll (char buf[],
	    const char src[], std::size_t slen,
	    const char dest[], std::size_t dlen) {
  for (char *p = buf; (p = std::strstr(p, src)); p += dlen) {
    replace_n(p, slen, dest, dlen);
  }
  
  return buf;
}

char *
replaceAll (char buf[], const char src[], const char dest[]) {
  return replaceAll(buf, src, std::strlen(src), dest, std::strlen(dest));
}

std::string &
replaceAll (std::string &s, const std::string &src, const std::string &dest) {
  std::string::size_type pos = s.find(src), slen = src.size(), dlen = dest.size();

  while (pos != std::string::npos)
    pos = s.replace(pos, slen, dest).find(src, pos + dlen);

  return s;
}

int main (int argc, char *argv[])
{
  using namespace std;

  char array[100] = "this is a test\0xxxxxxxxxxxxxxxxxxxxxxxxxxx";

  replace(array, "a test", "the best");
  cout << array << endl;

  replace(array, "the best", "a test");
  cout << array << endl;

  replaceAll(array, "i", "why");
  cout << array << endl;

  replaceAll(array, "why", "i");
  cout << array << endl;

  std::string s = "this is a test";
  replaceAll(s, "i", "why");
  cout << s << endl;

  replaceAll(s, "why", "i");
  cout << s << endl;

  return 0;
}