-1

これを行うために C++ を使用している間、最初の char から strlen(text)-1 までのコンテンツ全体をスキャンし、カンマと句読点をチェックできます。char が見つかった場合は、「スペース」またはその他の文字に置き換えることができます。

for(i=0;i<str.strlen();i++)
{
    if(ch[i] == ',' or [other])  //assume I have copied content of str in ch[]
       ch[i]=' ';
}

しかし、この機能を提供する C++ 関数またはクラスはありますか?

文字列、unordered_map、isstringstream、vector を扱っています。それぞれに独自の機能があります。しかし、これを上記の目的に使用できる人はいますか? または、他の何か?

4

5 に答える 5

8

std::replaceまたはstd::replace_ifを使用できます

std::replace(s.begin(), s.end(), ',' , ' ');
std::replace_if(s.begin(), s.end(), [](char c){return c == ','; }, ' ');

ライブサンプルを見る

C++03 の場合、次のことができます。

#include <cctype>   
struct IsComma
{
    bool operator()(char c) const
    {
        return (bool)std::ispunct(c);  //!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ as punctuation
    }
};

std::replace_if(s.begin(), s.end(), IsComma(), ' ');

忘れずに読むstd::ispunct

お役に立てれば!

于 2013-08-24T06:15:41.907 に答える
3

はい、標準文字列を使用できます。差し替え機能あり。ここで例を挙げることができます:

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

int main()
{
    string s = "The,quick,brown,fox,jumps,over,the,lazy,dog.";
    replace(s.begin(), s.end(), ',', ' '); // or any other character
    cout << s << endl;
    return 0;
}

出力は次のようになります。

The quick brown fox jumps over the lazy dog.
于 2013-08-24T06:16:05.263 に答える
2

使える:

//std::string input;

std::replace_if(input.begin(), input.end(), 
                 std::ptr_fun<int, int>(&std::ispunct), ' ');
于 2013-08-24T06:21:21.567 に答える
1

これは、これを行う古い C の方法です。非常に明示的ですが、必要なマッピングを簡単にプログラムできます。

char* myString = //Whatever you use to get your string
for(size_t i = 0; myString[i]; i++) {
    switch(myString[i]) {
        case ',':
        case '.':
        //Whatever other cases you care to add
            myString[i] = ' ';
        default:
    }
}
于 2013-08-24T08:16:08.857 に答える
1

std::ispunctchar が句読点文字であるかどうかを確認するために使用できます。

#include <iostream> 
#include <string>  
#include <locale>         // std::locale, std::ispunct
using namespace std;

int main ()
{
    locale loc;
    string str="Hello, welcome!";
    cout << "Before: " << str << endl;    
    for (string::iterator it = str.begin(); it!=str.end(); ++it)
        if ( ispunct(*it,loc) ) *it = ' ';
    cout << "After: " << str << endl;    
}
于 2013-08-24T06:18:00.650 に答える