c++ - CString 替换多个空白 MFC

标签 c++ cstring

我的 MFC 应用程序中有带有单个/多个空格的 CString。我必须用单下划线替换它们。 示例:sampleString=

"A B  C D   E" --> "A_B_C_D_E"

但是当我使用sampleString.Replace("",'_')时,每个空格都会出现下划线,即

"A_B__C_D___E".

我写了一段代码,但不太喜欢它,而且它是错误的。

                int i=0,pos=0,lastSpacePos=sampleString.GetLength();
                while(i<sampleString.GetLength())
                {
                    pos=sampleString.Find(" ",i);
                    if(pos!=-1)
                    {
                        if(lastSpacePos!=(pos-1))
                        {
                            sampleString.Delete(pos,1);
                            sampleString.Insert(pos,"_");
                        }                        
                        lastSpacePos=pos;
                        i=pos+1;
                    }
                    else
                        i++;
                }
                sampleString.Remove(' ');

还有我缺少的更简单的方法吗?

最佳答案

Replace返回找到的要替换的字符数,因此您可以尝试用一个空格替换两个空格,直到找不到更多空格对:

while(sampleString.Replace("  "," "));

然后用下划线替换一个空格:

sampleString.Replace(" ",'_');

关于c++ - CString 替换多个空白 MFC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22381913/

相关文章:

c++ - 区分带小数位的数字(double 类型)和不带小数位的数字 - C++

c++ - 为什么 SO_RCVTIMEO 从监听套接字继承到接受套接字?

c++ - gcc 预处理器 : can I resolve #if[def]s only, 保留其他指令不变?

mfc - CString最大长度

c++ - std::string 是如何实现的?

c++ - QVideoWidget是离开全屏后的新窗口

c++ - 尝试在 Vector 中查找内容时出错,不确定如何修复

c++ - MFC 的 CString 的奇怪行为

c++ - 在没有 cstring 的情况下比较 C++ 中的字符数组和字符串文字

c - strcmpi 代码不会编译但 strcmp 会?