【发布时间】:2012-06-16 22:59:30
【问题描述】:
所以我有一个子字符串函数,它接收子字符串的起始位置及其长度。这样,它应该提取其中的字符并将它们作为字符串返回,而无需实际使用任何字符串函数。
//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 世界并非永远存在
关于为什么它实际上没有从用户输入中输出没有额外字符的单词有什么想法吗?我迷路了。
【问题讨论】:
-
代码中的
String[i]是什么?你在this上给operator []打电话吗? -
试过调试器?
SearchString和TargetString有你期待的内容吗?Find和Length是否返回您期望的值? -
@mlt String 是类中的字符串,所以我猜你是对的。
-
@aschepler SearchString 和 TargetString 都是通过用户输入给出的字符串,Find 和 Length 都返回正确的值
-
你也应该在某个地方
delete[]ingsub。
标签: c++ string oop error-handling substring