2016-11-30 774 views
-3

如何在不使用任何庫函數的情況下以簡單方式從字符串中刪除標點符號和空格?C++從字符串中刪除標點符號和空格

+2

環繞字符串,跟蹤兩個位置:「寫入頭」和「讀取頭」。當讀取頭碰到標點符號時,無需書寫即可向前跳過。否則從讀頭複製到寫頭,並向前移動。 – BoBTFish

+1

標準庫也被禁止?和std :: string?標點符號只是「。,;:?!」或者它是不是字母數字的東西? – stefaanv

+0

@stefaanv什麼都不是字母數字 – lola96

回答

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; 
} 
+0

'std :: string :: operator []'是一個庫函數,所以這段代碼不符合不使用任何庫函數的要求。

1

假設你可以使用圖書館的I/O像<iostream>和類型,如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; 
} 

沒有關於性能的信息,我敢肯定它可以以多種更好的方式完成。

+0

恩,(明顯是人爲的)約束是不使用任何**庫函數。 'std :: string'的構造函數是一個庫函數。 而在幕後,for循環使用'std :: string :: begin()'和'std :: string :: end()',它們也是庫函數。 –

+1

那麼還不如去C風格並使用數組,甚至不得不使用'strlen()','strcat()'或者甚至是'printf()'等函數。我懷疑他的要求是嚴格的,但由於他沒有詳細猜測我們永遠不會知道。 – sharyex

+0

我懷疑的重點是編寫自己的'strlen'和'strcat'的等價物;他們並不那麼難。 'printf',另一方面,... –