2013-08-24 50 views
-1

使用C++執行此操作時,我們可以掃描第一個字符到strlen(文本)-1的整個內容並檢查逗號和標點符號。如果發現字符,那麼我們可以用「空格」或任何其他字符替換它。從文本內容跳過逗號和其他puncuation標記字符並將其替換爲空格

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,矢量。每個都有自己的功能。但是,有沒有人可以用於我的上述目的?或者是其他東西?

回答

2

能用途:

//std::string input; 

std::replace_if(input.begin(), input.end(), 
       std::ptr_fun<int, int>(&std::ispunct), ' '); 
+0

@POW:謝謝,這將適用於所有標點符號,對不對? – user123

+0

@Karimkhan是根據默認語言環境請參閱[this](http://en.cppreference.com/w/cpp/string/byte/ispunct) – P0W

+0

是的,我檢查了它!無論如何,你知道最喜歡的問題星星點擊嗎? – user123

8

你可以使用std::replacestd::replace_if

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

看到live sample

對於C++ 03,可以這樣做:

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

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

ALS不要忘了閱讀std::ispunct

希望這可以幫助!

+3

+1可能要利用['的std :: ispunct判斷()'](http://en.cppreference.com/w/cpp /字符串/字節/ ispunct)或一些這樣的獲得完整的遊戲。 – WhozCraig

+0

@WhozCraig不錯的提示! – billz

3

你可以使用std字符串,是的。有一個replace function。在這裏,我可以提供一個例子:

#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. 
+0

這將適用於單個測試值。對於它們的廣度(例如「所有標點符號」),將需要更多涉及的解決方案。但是,如果你只需要一個單一鏡頭直接替換* a *值,就很難打敗它。 – WhozCraig

+1

@WhozCraig:是的,我同意。希望,我有些幫助。 :) – lpapp

1

您可以使用std::ispunct檢查一個字符是否是標點字符:

#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;  
} 
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: 
    } 
} 
相關問題