您好,登錄后才能下訂單哦!
在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)閮蓚€字符串在忽略空格后是相等的。
免責(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)容。