1. 程式人生 > >字串相等的判斷(函式忽略大小寫,標點符號及空白字元)

字串相等的判斷(函式忽略大小寫,標點符號及空白字元)

個人比較喜歡的一個題目:

編寫一個函式,比較兩個字串的相等性,如果字串相等,函式應該返True,不等則返回False。函式應該忽略大小寫,標點符號及空白字元。用各種輸入測試你的函式。(摘自Absolute C++ 程式設計題第9.9題)

分析:

1.應該寫一個忽略大小寫的函式,一般的作法是,無論大小寫都轉換為小寫(個人的習慣吧),過程大概是遍歷字串的每一個字元,然後對其進行tolower()操作,tolower和toupper函式的注意事情在之前有介紹過了(當然此處和之前沒有什麼關係)。

2.忽略標點字元和空格,目前還沒學習正則表示式,而且也不知道C++有沒有(我所知道的python有),但是吃出我的作法是:將標點符號和空格放在一個字串(punct)裡面,然後在遍歷字串的時候,對每個字元,判斷是否出現在punct中即(punct.find()) ,如果不在其中說明則不是標點或空格,故將此字元push_back();

3.最後,把上述的兩個函式整合到題目要求的函式中,這個比較簡單,將直接在程式中體現。

源程式:

#include<iostream>
#include<string>
#include<cctype>
using namespace std;




string removePunct(const string &s,const string &punct);
string makelower(const string &s);
bool Isequal(const string &s1,const string &s2);


int main()
{
string s1;
string s2;
getline(cin,s1);
getline(cin,s2);

cout<< Isequal(s1,s2);


return 0;
}


string removePunct(const string &s,const string &punct)
{
string noPunct;
int slength=s.length();
int i;
int punctlength=punct.length();

for(i=0;i<slength;i++)
{
string achar=s.substr(i,1);
int location=punct.find(achar,0);//在punct裡面找,如果是,則location返回正常值 
//若超出或者《0 ,則說明不在nopunct中,故儲存下來 
if(location<0||location>=punctlength)
{
noPunct=noPunct+achar;//之所以achar選擇為string的原因是在這可以做更安全的連線 
}
}


return noPunct;
}




string makelower(const string &s)
{
int i;
string temp(s);

for( i=0;i<s.length();i++)
{
temp[i]=tolower(s[i]);
}

return temp;
}


bool Isequal(const string &s1,const string &s2)
{
string punct(",.;?!'\" ");
string str1(s1);
string str2(s2);
str1=makelower(str1);
str2=makelower(str2);
string lowerstr1=removePunct(str1,punct);
string lowerstr2=removePunct(str2,punct);

return lowerstr1==lowerstr2;
}


測試用例:(歡迎補充)