添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

教程

Python 3 Basic Python Advanced Tkinter Python Modules JavaScript Python Numpy Git Matplotlib PyQt5 Data Structure Algorithm

貼士文章

Rust Python Pygame Python Python Tkinter Batch PowerShell Python Pandas Numpy Python Flask Django Matplotlib Plotly Docker Seaborn Matlab Linux Git C Cpp HTML JavaScript jQuery TypeScript Angular React CSS PHP Java Go Node.js Kotlin Csharp Ruby Arduino MongoDB MySQL Postgres R VBA Scala Raspberry Pi

函數參考

Python Pandas Numpy

使用 erase-remove 習慣用法從 C++ 中的字串中刪除空格

C++ 中用於範圍操作的最有用的方法之一是 erase-remove 習慣用法,它包含兩個函式- std::erase (大多數 STL 容器的內建函式)和 std::remove (STL 演算法庫的一部分)。請注意,它們都連結在一起以對給定的物件執行刪除操作。 std::remove 函式需要兩個迭代器來指定範圍,第三個參數列示要刪除的元素的值。在這種情況下,我們直接指定一個空格字元,但是可以指定任何字元以刪除字串中所有出現的字元。

#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
  string str = "  Arbitrary   str ing with lots of spaces to be removed   .";
  cout << str << endl;
  str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
  cout << str << endl;
  return EXIT_SUCCESS;
Arbitrary   str ing with lots of spaces to be removed   .
Arbitrarystringwithlotsofspacestoberemoved.

另一方面,使用者也可以將一元謂詞作為第三個引數傳遞給 std::remove 演算法。謂詞應為每個元素求出布林值,並且當結果為 true 時,將從範圍中刪除相應的值。因此,我們可以利用預定義的 isspace 函式來檢查多個空格字元,例如空格-" ",換行符-\n,水平製表符-\t 以及其他幾個字元。

#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
  string str = "  Arbitrary   str ing with lots of spaces to be removed   .";
  cout << str << endl;
  str.erase(std::remove_if(str.begin(), str.end(), isspace), str.end());
  cout << str << endl;
  return EXIT_SUCCESS;
Arbitrary   str ing with lots of spaces to be removed   .
Arbitrarystringwithlotsofspacestoberemoved.

在 C++ 中使用自定義函式從字串中刪除空格

請注意,所有以前的解決方案都修改了原始的字串物件,但是有時,可能需要建立一個刪除所有空格的新字串。我們可以使用相同的 erase-remove 慣用語來實現自定義函式,該慣用語接受字串引用並返回已解析的值,以將其儲存在單獨的字串物件中。也可以修改此方法以支援另一個函式引數,該引數將指定需要刪除的字元。

#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
string removeSpaces(const string& s) {
  string tmp(s);
  tmp.erase(std::remove(tmp.begin(), tmp.end(), ' '), tmp.end());
  return tmp;
int main() {
  string str = "  Arbitrary   str ing with lots of spaces to be removed   .";
  cout << str << endl;
  string newstr = removeSpaces(str);
  cout << newstr << endl;
  return EXIT_SUCCESS;
Arbitrary   str ing with lots of spaces to be removed   .
Arbitrarystringwithlotsofspacestoberemoved.
    
作者: Jinku Hu

DelftStack.com 創辦人。Jinku 在機器人和汽車行業工作了8多年。他在自動測試、遠端測試及從耐久性測試中創建報告時磨練了自己的程式設計技能。他擁有電氣/ 電子工程背景,但他也擴展了自己的興趣到嵌入式電子、嵌入式程式設計以及前端和後端程式設計。

LinkedIn Facebook