问答题 请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程prog3,其中声明的MyString类是一个用于表示字符串的类。成员函数endsWith的功能是判断此字符串是否以指定的后缀结束,其参数s用于指定后缀字符串。如果参数s表示的字符串是MyString对象表示的字符串的后缀,则返回true;否则返回false。注意,如果参数s是空字符串或等于MyString对象表示的字符串,则结果为true。例如,字符串“cde”是字符串“abcde”的后缀,而字符串“bde”不是字符串“abcde”的后缀。请编写成员函数endsWith。在main函数中给出了一组测试数据,此种情况下程序的输出应为:s1=abcdes2=cdes3=bdes4=s5=abcdes6=abcdefs1endsWiths2:trues1endsWiths3:falses1endsWiths4:trues1endsWiths5:trues1endsWiths6:false要求:补充编制的内容写在“//**********333**********”与“//**********666**********”之间。不得修改程序的其他部分。注意:程序最后将结果输出到文件out.dat中,输出函数writeToFile已经编译为obj文件,并且在本程序中调用。//Mystring.h#include<iostream>#include<string.h>usingnamespacestd;classMyString{public:MyString(constchar*s){Size=strlen(s);str=newchar[size+1];strcpy(str,s);}~MyString()(delete[]str;}boolendsWith(constchar*s)const;private:char*Str;intsize;};voidwriteTOFile(constchar*);//main.cpp#include"MyString.h"boolMyString::endsWith(constchar*s)const{//********333********//********666********}intmain(){chars1[]="abcde";chars2[]="cde";chars3[]="bde";chars4[]=…';chars5[]="abcde";chars6[]="abcdef";MyStringstr(s1);cout<<"s1="<<s1<<end1<<"s2="<<s2<<end1<<"s3="<<s3<<end1<<"s4="<<s4<<end1<<"s5="<<s5<<end1<<"s6="<<s6<<end1;cout<<b001aipha<<"s1endSWiths2:"<<Str.endsWith(s2)<<end1<<"s1endSWiths3:"<<Str.endsWith(s3)<<end1<<"s1endSWiths4:"<<Str.endsWith(s4)<<end1<<"s1endSWiths5:"<<Str.endsWith(s5)<<end1<<"s1endSWithS6:"<<Str.endsWith(s6)<<end1;writeToFile("");return0;}
【正确答案】正确答案:int s_size = strlen(s); for (int i = 0; i < s_size; i++) if (str[size - s_size + i] != s[i]) return false; return true;
【答案解析】解析:主要考查考生对字符串的掌握情况,根据题目要求可知,函数用来判断此字符串是否以指定的后缀结束。判断过程是先求形参的长度,从形参的第一个字符开始判断字符串是否一致。该函数是bool函数,最后要确定是返回true还是false。