求兼容Microsoft Visual C++2008的CString连续4位数字替换函数
Solution for Replacing Consecutive 4-Digit Sequences in CString (VC2008 Compatible)
Since Visual C++ 2008 has really limited regex support (the standard <regex> header wasn't fully implemented until later MSVC versions), a custom string traversal approach is the most reliable way to handle this without external dependencies. Below is a function that works seamlessly with MFC's CString and fits your exact requirements:
CString ReplaceConsecutiveFourDigits(CString input) { CString result; int currentDigitRunLength = 0; int digitRunStartPos = -1; for (int i = 0; i < input.GetLength(); ++i) { TCHAR currentChar = input[i]; if (_istdigit(currentChar)) { if (currentDigitRunLength == 0) { // Mark the start of a new sequence of digits digitRunStartPos = i; } currentDigitRunLength++; } else { // We've hit a non-digit; process the current digit sequence if there is one if (currentDigitRunLength > 0) { if (currentDigitRunLength >= 4) { // Replace first 4 digits with ****, append remaining digits result += _T("****"); result += input.Mid(digitRunStartPos + 4, currentDigitRunLength - 4); } else { // Keep short digit sequences as-is result += input.Mid(digitRunStartPos, currentDigitRunLength); } // Reset tracking variables for next sequence currentDigitRunLength = 0; digitRunStartPos = -1; } // Add the non-digit character to the result result += currentChar; } } // Handle the edge case where the string ends with a digit sequence if (currentDigitRunLength > 0) { if (currentDigitRunLength >= 4) { result += _T("****"); result += input.Mid(digitRunStartPos + 4, currentDigitRunLength - 4); } else { result += input.Mid(digitRunStartPos, currentDigitRunLength); } } return result; }
How It Works
- Tracking Digit Sequences: We traverse each character in the input
CString, keeping track of when we enter a sequence of digits, its start position, and its length. - Processing Sequences: When we hit a non-digit character (or reach the end of the string), we check the length of the current digit sequence:
- If it's 4 or more digits long: We append
****followed by any digits beyond the first 4. - If it's shorter than 4 digits: We append the entire sequence as-is.
- If it's 4 or more digits long: We append
- Compatibility: Uses
_istdigit(a VC-compatible macro that works for both Unicode and ANSI builds) and standardCStringmethods (GetLength,Mid) that are fully supported in VC2008.
Test It With Your Example
If you pass your sample input:
CString original = _T("1234567 12 34 78 iioi78ccc8888 aaassd dededeed ed"); CString processed = ReplaceConsecutiveFourDigits(original);
The processed string will be exactly what you need:****567 12 34 78 iioi78ccc**** aaassd dededeed ed
Notes
- This works for both MFC and ATL
CStringimplementations, since both have the required methods. - No external libraries or regex dependencies are needed—perfect for legacy VC2008 projects.
内容的提问来源于stack exchange,提问作者Dan.Gurghian
相关产品推荐
相关产品推荐

