所以我有一个子字符串函数,它接受子字符串的起始位置及其长度。有了它,它应该提取其中的字符并将它们作为字符串返回,而不实际使用任何字符串函数。
//default constructor that sets the initial string to the value "Hello World"
MyString::MyString()
{
char temp[] = "Hello World";
int counter(0);
while(temp[counter] != '\0')
{
counter++;
}
Size = counter;
String = new char [Size];
for(int i=0; i < Size; i++)
String[i] = temp[i];
}
//copy constructor
MyString::MyString(const MyString &source)
{
int counter(0);
while(source.String[counter] != '\0')
{
counter++;
}
Size = counter;
String = new char[Size];
for(int i = 0; i < Size; i++)
String[i] = source.String[i];
}
这是我的子字符串函数:
MyString MyString::Substring(int start, int length)
{
char* leo = new char[length+1];
for(int i = start; i < start + length+ 1; ++i)
{
leo[i-start] = String[i];
}
MyString sub;
delete [] sub.String;
sub.String = leo;
sub.Size = length+1;
return sub;
}
使用 main.cpp 文件中的代码:
int main (int argc, char **argv)
{
MyString String1; // String1 must be defined within the scope
const MyString ConstString("Target string"); //Test of alternate constructor
MyString SearchString; //Test of default constructor that should set "Hello World".
MyString TargetString (String1); //Test of copy constructor
cout << "Please enter two strings. ";
cout << "Each string needs to be shorter than 256 characters or terminated by /\n." << endl;
cout << "The first string will be searched to see whether it contains exactly the second string. " << endl;
cin >> SearchString >> TargetString; // Test of cascaded string-extraction operator
if(SearchString.Find(TargetString) == -1) {
cout << TargetString << " is not in " << SearchString << endl;
}
else {
cout << TargetString << " is in " << SearchString << endl;
cout << "Details of the hit: " << endl;
cout << "Starting position of the hit: " << SearchString.Find(TargetString) << endl;
cout << "The matching substring is: " << SearchString.Substring(SearchString.Find(TargetString), TargetString.Length()-1)<<"\n";
}
它返回:
请输入两个字符串。每个字符串必须少于 256 个字符或以 / 结尾。将搜索第一个字符串以查看它是否正好包含第二个字符串。
永远
更多的
morev 世界并非永远存在
关于为什么它实际上没有从用户输入中输出没有额外字符的单词有什么想法吗?我迷路了。