2016-11-30 773 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',另一方面,... –