溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++字符串比較忽略空格

發(fā)布時間:2024-10-09 15:27:16 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

在C++中,如果要比較兩個字符串并忽略其中的空格,可以先將字符串中的空格刪除,然后再進(jìn)行比較。下面是一種實(shí)現(xiàn)方法:

#include <iostream>
#include <string>
#include <algorithm>

bool compareIgnoreSpace(const std::string &str1, const std::string &str2) {
    std::string str1NoSpace, str2NoSpace;

    // 刪除字符串中的空格
    std::remove(str1.begin(), str1.end(), ' ');
    std::remove(str2.begin(), str2.end(), ' ');

    // 比較處理后的字符串是否相等
    return str1NoSpace == str2NoSpace;
}

int main() {
    std::string str1 = "Hello World";
    std::string str2 = "Hello  World";

    if (compareIgnoreSpace(str1, str2)) {
        std::cout << "Strings are equal (ignoring spaces)" << std::endl;
    } else {
        std::cout << "Strings are not equal" << std::endl;
    }

    return 0;
}

在這個示例中,compareIgnoreSpace函數(shù)接受兩個字符串參數(shù),并使用std::remove算法將它們中的空格刪除。然后,它比較處理后的字符串是否相等。在main函數(shù)中,我們定義了兩個包含空格的字符串,并使用compareIgnoreSpace函數(shù)進(jìn)行比較。輸出結(jié)果將是“Strings are equal (ignoring spaces)”,因?yàn)閮蓚€字符串在忽略空格后是相等的。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI