请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程prog3,其中声明了MyString类。MyString是一个用于表示字符串的类。成员函数startsWith的功能是判断此字符串是否以指定的前缀开始,其参数8用于指定前缀字符串。如果参数s表

admin2015-06-27  28

问题 请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程prog3,其中声明了MyString类。MyString是一个用于表示字符串的类。成员函数startsWith的功能是判断此字符串是否以指定的前缀开始,其参数8用于指定前缀字符串。如果参数s表示的字符串是MyString对象表示的字符串的前缀,则返回true;否则返回false。注意,如果参数S是空字符串或等于MyString对象表示的字符串,则结果为true。
例如,字符串“abc”是字符串“abcde”的前缀,而字符串“abd”不是字符串“abcde”的前缀。请编写成员函数startsWith。在main函数中给出了一组测试数据,此种情况下程序的输出应为:
s1=abcde
s2=abc
s3=abd
s4=
s5=abcde
s6=abcdef
s1startsWiths2:true
s1startsWiths3:false
s1startsWiths4:true
s1startsWiths5:true
s1startsWiths6:false
要求:
补充编制的内容写在“//**********333**********”与“//**********666**********”之间,不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中。输出函数writeToFile已经编译为obj文件,并且在本程序中调用。
//MyStving.h
#include
#include
usingnamespacestd;
classMyString{
public:
MyString(constchar*s)
{
size=strlen(s);
str=newchar[size+1];
strcpy(str,s);
}
~MyString(){delete[]str;)
boolstartsWith(constchar*s)
const;
private:
char*str;
intSize;
};
voidwriteToFile(constchar*);
//main.cpp
#include"MyString.h"
boolMyString::startsWith(const
char*s)const
{
//********333********
//********666********
}
intmain()
{
chars1[]="abcde";
chars2[]="abc";
chars3[]="abd";
chars4[]="";
chars5[]="abcde";
chars6[]="abcdef";
MyStringstr(s1);
cout<<"s1="<<<"s2="<<<"s3="<<<"s4="<<<"s5="<<<"s6="<cout<<<"s1startSWiths2:"<<<"s1startSWiths3:"<<<"s1StartSWiths4:"<<<"s1startSWiths5:"<<<"s1StartsWiths6:"<writeToFile("");
return0;
}

选项

答案if (s == NULL) return true; int len = strlen(s); if (len > size) return false; for (int i = 0; i < len; i++) if ( str[i] != s[i]) return false; return true;

解析 主要考查考生对动态数组的掌握情况,根据题目要求知,函数的功能是判断此字符串是否以指定的前缀开始。利用for循环,逐个字符进行判断,如果满足条件str != s,返回false,否则返回true。
转载请注明原文地址:https://kaotiyun.com/show/GRNp777K
0

最新回复(0)