4

次のコードは、char 配列から句読点を正しく削除しました。

#include <cctype>
#include <iostream>

int main()
{
    char line[] = "ts='TOK_STORE_ID'; one,one, two;four$three two";
    for (char* c = line; *c; c++)
    {
        if (std::ispunct(*c))
        {
            *c = ' ';
        }
    }
    std::cout << line << std::endl;
}

lineがタイプの場合、このコードはどのように見えるでしょうstd::stringか?

4

4 に答える 4

6

単純に STL アルゴリズムを使用する場合は、次のようになります。

#include<algorithm>

std::string line ="ts='TOK_STORE_ID'; one,one, two;four$three two";

std::replace_if(line.begin() , line.end() ,  
            [] (const char& c) { return std::ispunct(c) ;},' ');

または、STL を使用したくない場合

単純に使用します:

std::string line ="ts='TOK_STORE_ID'; one,one, two;four$three two";
std::size_t l=line.size();
for (std::size_t i=0; i<l; i++)
{
    if (std::ispunct(line[i]))
    {
        line[i] = ' ';
    }
}
于 2013-08-31T09:10:04.680 に答える
6
#include <iostream>
#include<string>
#include<locale>

int main()
{
    std::locale loc;
    std::string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";

    for (std::string::iterator it = line.begin(); it!=line.end(); ++it)
            if ( std::ispunct(*it,loc) ) *it=' ';

    std::cout << line << std::endl;
}
于 2013-08-31T09:14:16.650 に答える
5

使用できますstd::replace_if

bool fun(const char& c)
{
  return std::ispunct(static_cast<int>(c));
}

int main()
{
  std::string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";
  std::replace_if(line.begin(), line.end(), fun, ' ');
}
于 2013-08-31T09:09:36.373 に答える
3

これがお役に立てば幸いです

#include <iostream>
#include<string>
using namespace std;
int main()
{
    string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";
    for (int i = 0;i<line.length();i++)
    {
        if (ispunct(line[i]))
        {
            line[i] = ' ';
        }
    }
    cout << line << std::endl;
    cin.ignore();
}
于 2013-08-31T09:14:50.477 に答える