First of all, CString doesn’t have a direct member function for this. But at times we will need this functionality and it is not that particular not to add it as a member if they can add functions like SpanIncluding, Replace etc. So lets discuss some ways which I found that can get the job done.
SpanIncluding/SpanExcluding
NO!!! This is not even a way to do it. One can think that what if we use SpanExcluding using the character we want as a delimiter and subtract the length of resultant string from the length of original string. Similar is the case for SpanIncluding. Now, listen to this! These functions will not return all the characters other than the delimiters. Its somewhat continuous. For example, calling SpanExluding for string “abc:cd” with delimiter “:” will return string “abc” only. Same is the case with SpanIncluding.
Remove/Replace
This is the most easiest way in terms of lines of code. Both function returns the count of the character that is replaced or removed. Take care to make a copy of the string before doing this. It involves editing of the string; especially the Remove function requires shifting of characters after the removed character. So this method is not suitable for large strings as it can cause performance hit.
Find (recommended)
I searched a lot for a function that works like magic in a single line of code. The conclusion as I could find was, There is no highway option! The best thing you can do is to use Find function in a while loop to find each character. Is that complex? here’s the code:
int CharacterCount( CString& csString_i, LPCTSTR sChar_i ) { if( csString_i.IsEmpty() || L"" == sChar_i ) { return 0; } int nFind = -1; int nCount = 0; while( -1 != ( nFind = csString_i.Find( sChar_i, nFind + 1 ))) { nCount++; } return nCount; }
Got a better way? Please give your thoughts as comments.
You can also use AfxExtractSubstring but ultimately it’s using CString::Find. Find is the best and straightforward option – http://msdn.microsoft.com/en-us/library/aa991543%28v=vs.80%29.aspx
Yes, Considering the higher priority for code readability and performance rather than lines of code, CString::Find seems to be the best option! Thanks!
I find that:
int count = strVar.Replace(“targ”, “targ”);
works fine. The result is the same string, and the count has the number of times “targ” appears in the original (and final) strVar.
genius! Works find to me. thanks!!
Kill the spammer!
int count = strVar.Replace(“targ”, “targ”); works for me
This Does Not work For CString , it checks if the new char is not the same as the old one before replacing them
so if they are identical the count will always equal zero!
Replace counted right even if the strings were the same.