0

I am trying to build a recursive funciton using static variable that would replace white space with asterik character however soemthing is amiss. I get error Runtime error time: 0 memory: 3472 signal:11.

Code

#include <iostream>
using namespace std;

string replace(string s) {
    static int n = 0;

    if (n == s.length()) return s; 
    if (s[n] == ' ') s[n] = '*';

    n++;
    replace(s);
}

int main() {
    string s= "ssdfa sadfs";
    cout<<replace(s);
    return 0;
}
Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168
  • OT: http://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar Oct 25 '14 at 02:47
  • If you want to make it recursive, why to calculate string leangh every time. You should pass string length as parameter to function. It will increase your computation time. Your function header should be like this ` string replace(string s, int len)` – Shravan40 Oct 25 '14 at 02:49
  • 1
    So how would I be able to call `replace` more than once in a program? Write it without the `static` variable. – PaulMcKenzie Oct 25 '14 at 02:52
  • You would need a wrapper function and another function that would be like `int count(string s, int n)` and this wrapper function would be like `string replace(string s) { return count(s,0); }` – Muhammad Umer Oct 25 '14 at 02:53
  • 2
    @Shravan40 `std::string` doesn't need to calculate the length, it's a member of the structure. It's not like C strings, which require you to search for the terminator. – Barmar Oct 25 '14 at 02:57

2 Answers2

2

You're only returning a string from the base case of the recursion, not all the other cases. Change the last line to:

return replace(s);
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

This can simply be done like this

string replace(string s)
{
    int len = s.length();
    for(int i = 0; i < len; i++)
    {
        if(s[i] == ' ')
            s[i] = '*';
    }
    return s;
}
Shravan40
  • 8,922
  • 6
  • 28
  • 48