溫馨提示×

c++ string庫函數(shù)能否去除字符串首尾空格

c++
小樊
81
2024-09-24 22:22:02
欄目: 編程語言

是的,C++的<string>庫中的strip()函數(shù)可以去除字符串首尾的空格。

該函數(shù)屬于std::string類,其語法為:

std::string& strip(std::string& s);
const std::string& strip(const std::string& s);

其中,第一個版本的函數(shù)會修改傳入的字符串對象,第二個版本的函數(shù)則不會修改傳入的字符串對象,而是返回一個新的字符串對象。

該函數(shù)的功能是去除字符串首尾的所有空白字符,包括空格、制表符、換行符等等。

以下是一個使用示例:

#include <iostream>
#include <string>

int main() {
    std::string str = "   Hello, World!   ";
    std::cout << "Original string: [" << str << "]" << std::endl;
    str.strip();
    std::cout << "Striped string: [" << str << "]" << std::endl;
    return 0;
}

輸出結果為:

Original string: [   Hello, World!   ]
Striped string: [Hello, World!]

0