您的位置:首页 > 其它

字符串相等的判断(函数忽略大小写,标点符号及空白字符)

2014-09-12 14:08 477 查看
个人比较喜欢的一个题目:

编写一个函数,比较两个字符串的相等性,如果字符串相等,函数应该返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;

}

测试用例:(欢迎补充)













内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐