所以我有一个子字符串函数,它接受子字符串的开始位置及其长度。有了它,它应该提取其中的字符并以字符串形式返回它们,而不实际使用任何字符串函数。

//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个字符或以/结尾

将搜索第一个字符串以查看它是否完全包含第二个字符串。

永远

更多

世界不会永远存在

关于为什么它实际上不从用户输入中输出没有多余字符的单词有什么想法?我迷路了。

最佳答案

for(int i = start; i < length+1; i++)

这无法按照您想要的方式工作。它应该是:
for (int i = start; i < start + length; ++i)

您遇到了一个错误的错误,并且一旦意识到这是什么意思,结束条件就没有意义了。

取一个从索引2开始的子字符串,其长度为5。要复制的字符在索引2到6中,这符合条件。

在内部,您还有另一个问题。除非i从0开始,否则您不会复制到适当的数组索引中。它应该是:
sub [i - start] = String [i];

这样,您将开始在索引0处填充sub

另外,完成后,您需要将其空终止:
sub [length] = '\0';

这样,它就不会结束。

09-04 17:17
查看更多