C ++从字符串中删除标点符号和空格

时间:2016-11-30 08:01:12

标签: c++

如何在不使用任何库函数的情况下以简单的方式从字符串中删除标点符号和空格?

2 个答案:

答案 0 :(得分:1)

假设您可以使用<iostream>之类的库I / O和类似std::string的类型,并且您不想使用<cctype>ispunct()函数。

#include <iostream>
#include <string>


int main()
{
    const std::string myString = "This. is a string with ,.] stuff in, it.";
    const std::string puncts = " [];',./{}:\"?><`~!-_";
    std::string output;

    for (const auto& ch : myString)
    {
        bool found = false;

        for (const auto& p : puncts)
        {
            if (ch == p)
            {
                found = true;
                break;
            }
        }

        if (!found)
            output += ch;
    }

    std::cout << output << '\n';

    return 0;
}

不知道性能,我确信它可以通过多种更好的方式完成。

答案 1 :(得分:0)

int main()
{
    string s = "abc de.fghi..jkl,m no";
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == ' ' || s[i] == '.' || s[i] == ',')
        {
            s.erase(i, 1); // remove ith char from string
            i--; // reduce i with one so you don't miss any char
        }
    }
    cout << s << endl;
}