replace chr in string - fault

Hi
Am trying to replace a character with another character in a pointer string.
The function should return the number of occurrences modified.

A runtime error "Segmentation fault (core dump)".

Any suggestions why?


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
#include <iostream>

unsigned int replace (char *, char, char);

int main() {

  char str[] = "Hello World";
  char c1{'l'};
  char c2{'x'};

  unsigned int i = replace(str, c1, c2);

  std::cout << "Modified string: " << str << std::endl;
  std::cout << "Number of characters modified : " << i << std::endl;
  return 0;
}

unsigned int replace(char * str, char c1, char c2) {
  unsigned int count{0};
  unsigned i{0};

  while (*str) { // quit when *str is '\0'
    if (str[i] == c1) {
      *(str + i) = c2; 
      count++;
    }   
    i++;
  }
 
   return count;
 }
while (*str)
You should be testing for str[i] (or, if you prefer, *(str+i) to be zero.

thanks, modified as follows, and it works!

1
2
3
4
5
6
7
8
9
10
11
12
unsigned int replace(char * str, char c1, char c2) {
  unsigned int count{0};
  while (*str) { // quit when *str is '\0'
    if (*str == c1) {
      *str = c2;
      count++;
    }
    str++;
  }
 
   return count;
}
Topic archived. No new replies allowed.