Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ลบช่องว่างออกจาก std::string ใน C++


ในโปรแกรมนี้ เราจะมาดูวิธีการลบช่องว่างออกจาก std::string ใน C++ ในการลบสิ่งนี้ เราจะใช้ฟังก์ชัน remove() ด้วยฟังก์ชัน remove() นี้ จะใช้จุดเริ่มต้นและจุดสิ้นสุดของตัววนซ้ำ จากนั้นจึงรับอาร์กิวเมนต์ที่สามที่จะถูกลบออกจากออบเจกต์ iterator

Input: A string "This is C++ Programming Language"
Output: "ThisisC++ProgrammingLanguage"

อัลกอริทึม

Step 1: Get the string
Step 2: Remove spaces from the given string using remove() function.
Step 3: Return string.

โค้ดตัวอย่าง

#include<iostream>
#include<algorithm>
using namespace std;
main() {
   string my_str = "This is C++ Programming Language";
   cout << "String with Spaces :" << my_str << endl;
   remove(my_str.begin(), my_str.end(), ' ');
   cout << "String without Spaces :" << my_str;
}

ผลลัพธ์

String with Spaces :This is C++ Programming Language
String without Spaces :ThisisC++ProgrammingLanguage