cStrings删除非alpha /非空格字符 - C ++

时间:2014-11-20 05:39:39

标签: c++ c cstring c-strings

所以我需要创建一个从字符串(c-string)中删除所有非字母和非空格字符的函数。

例如:"我很不高兴,2014年11月15日,我的2辆全新BMW 750L被盗了!"应该变成"我很不高兴,因为我的全新宝马被盗了#34;

documentCopy[201] = "I'm upset that on Nov. 15th, 2014, my 2 brand-new BMW 750Lis were stolen!!";

for (int i = 0; documentCopy[i] != '\0'; i++)
{
    if (!isalpha(documentCopy[i]) && !isspace(documentCopy[i]))
    {

        for (int k = i; documentCopy[k] != '\0'; k++)
        {
            documentCopy[k] = documentCopy[k+1];

        }
    }
}
cout << documentCopy << endl;

不幸的是输出是&#34;我很不高兴在11月5日04我的全新BMW 5Lis被盗了!&#34;

请帮忙!

5 个答案:

答案 0 :(得分:2)

以下代码忽略所有空格并删除所有非字符:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {

    std::string str = "I'm upset that on Nov. 15th, 2014, my 2 brand-new BMW 750Lis were stolen!!";
    str.erase(std::remove_if(str.begin(), str.end(), [](const unsigned &c){ return !isspace(c) && !isalpha(c);}), str.end());
    std::cout << str;
    return 0;
}

输出将是:

  

我很不高兴在11月份我的全新宝马Lis被盗了

如果必须:

,您还可以在C字符串上使用remove_if
char cstring[] = "I'm upset that on Nov. 15th, 2014, my 2 brand-new BMW 750Lis were stolen!!";
int count = 0;
std::remove_if(cstring, cstring+sizeof(cstring), [&count](const unsigned char &c)
                                            {
                                                if (!isspace(c) && !isalpha(c))
                                                {
                                                    ++count;
                                                    return true;
                                                }
                                                else
                                                    return false;                               
        });

cstring[sizeof(cstring) - count] = 0;

std::cout << cstring;

答案 1 :(得分:1)

在此循环之后的一行之后

for (int k = i; documentCopy[k] != '\0'; k++)
{
    documentCopy[k] = documentCopy[k+1];
}
i--;  //Add This line in your Code.

这样可行。

例如,

如果您正在检查a[0]并转移a[0] = a[1] 因此,您需要再次检查a[0],因为现在它正在保持a[1]的值,因此需要降低索引值。

答案 2 :(得分:1)

当你丢弃一个角色时,你会复制下一个角色,但是你想要考虑是否也应该丢弃下一个角色。要做到这一点,你需要在这种情况下避免++i,即:

for (int i = 0; documentCopy[i] != '\0'; )
{
    if (!isalpha(documentCopy[i]) && !isspace(documentCopy[i]))
    {

        for (int k = i; documentCopy[k] != '\0'; k++)
        {
            documentCopy[k] = documentCopy[k+1];
        }
    }
    else
        ++i;
}

答案 3 :(得分:1)

void Voila()
{
    char documentCopy[] = "I'm upset that on Nov. 15th, 2014, my 2 brand-new BMW 750Lis were stolen!!";
    char* psrc = documentCopy;
    char* pdst = documentCopy;

    for( ; *psrc; ++psrc)
    {
        if (isalpha(*psrc) || isspace(*psrc))
            *pdst++ = *psrc;
    }
    *pdst = 0;
    cout << documentCopy << endl;
}

答案 4 :(得分:0)

一旦找到非空格和非字母字符,就会将整个字符串向左移动一个位置,然后i递增,不再指向到达不需要的字符位置的新字符。如果有连续不需要的字符(非空格和非字母)您的代码将无法检测到它。