Search code examples
c++replacefindc-strings

c++ cstring find and replace


I have a C++ project (Microsoft Visual C++ 2008) that was developed years ago by a colleague of mine and I need to update something.

I have a CString that contains a json and I need to find and replace every combination of 4 consecutive numbers that is present with ****.

Example string

1234567 12 34 78 iioi78ccc8888 aaassd dededeed ed

Resulting string

****567 12 34 78 iioi78ccc**** aaassd dededeed ed

Can you suggest a function that can effectively do this, that is fully compatible with Microsoft Visual C++ 2008.

Thank you.

P.S. My approach would be to use RegEX to find the list of 4 consecutive digits and to replace them but support for Microsoft Visual C++ 2008 is limited – as I was reading.


Solution

  • This is pretty trivial to write manually:

    const int DIGIT_COUNT = 4;
    int length = strlen(input);
    int consecutiveDigits = 0;
    for (int i = 0; i < length; ++i)
    {
       if (isDigit(input[i]))
         consecutiveDigits++;
       else
         consecutiveDigits = 0;
    
       if (consecutiveDigits == DIGIT_COUNT)
         for (int j = 0; j < 4; ++j)
           input[i - j] = '*';
    }
    

    Add an isDigit(char) function and you're good.