问答题
请使用VC6或使用[答题]菜单打开考生文件夹proj3下的工程prog3,其中声明的MyString类是一个用于表示字符串的类。成员函数endsWith的功能是判断此字符串是否以指定的后缀结束,其参数s用于指定后缀字符串。如果参数S表示的字符串是MyString对象表示的字符串的后缀,则返回true;否则返回false。注意,如果参数s是空字符串或等于MyString对象表示的字符串,则结果为true。
例如,字符串“cde”是字符串“abcde”的后缀,而字符串“bde”不是字符串“abcde”的后缀。请编写成员函数endsWith。在main函数中给出了一组测试数据,此种情况下程序的输出应为:
s1=abcde
s2=cde
s3=bde
s4=
s5=abcde
s6=abcdef
s1 endsWith s2:true
s1 endsWith s3:false
s1 endsWith s4:true
s1 endsWith s5:true
s1 endsWith s6:false
要求:
补充编制的内容写在“//********333********”与“//********666********”之间。不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中,输出函数writeToFile已经编译为obj文件,并且在本程序中调用。
//Mystring.h
#include <iostream>
#include <string.h>
using namespace std;
class MyString {
public:
MyString(const char* s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
}
~MyString() { delete [] str;}
bool endsWith(const char* s) const;
private:
char* str;
int size;
};
void writeToFile(const char * );
//main.cpp
#include "MyString.h"
bool MyString::endsWith (const char* s) const
{
//******** 333********
//******** 666********
}
int main ()
{
char s1[] = "abcde";
char s2[] = "cde";
char s3[] = "bde";
char s4[] = "" ;
char s5[] = "abcde";
char s6[] = "abcdef";
MyString str (s1);
cout << "s1 = " << s1 << endl
<< "s2 = " << s2 << endl
<< "s3 = " << s3 << endl
<< "s4 = " << s4 << endl
<< "s5 = " << s5 << endl
<< "s6 = " << s6 << endl;
cout << boolalpha
<< "s1 endsWith s2 :" << str.endsWith(s2) << endl
<< "s1 endsWith s3 :" << str.endsWith(s3) << endl
<< "s1 endsWith s4 :" << str.endsWith(s4) << endl
<< "s1 endsWith s5 :" << str.endsWith(sS) << endl
<< "s1 endsWith s6 :" << str.endsWith(s6) << endl;
writeToFile ("");
return 0;
}
【正确答案】int s_size=strlen(s); //把字符串s的长度赋值给s_size
for(int i=0; i<s_size; i++) //i从0到s_size-1开始遍历
if(str[size-s_size+i] !=s[i]) //如果str[size_s_size+i]不等于s[i]
return false; //返回false
return true; //否则返回true
【答案解析】[考点] 本题考查的是MyString类,其中涉及构造函数、析构函数和bool函数。
[解析] 主要考查考生对字符串的掌握情况,根据题目要求可知,函数用来判断此字符串是否以指定的后缀结束。判断过程是先求形参的长度,从形参的第一个字符开始判断字符串是否一致。该函数是bool函数,最后要确定是返回true还是false。