gpt4 book ai didi

c++ - 在类中使用C++返回子字符串

转载 作者:行者123 更新时间:2023-12-03 09:03:52 25 4
gpt4 key购买 nike

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

//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';

这样,它就不会结束。

关于c++ - 在类中使用C++返回子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11067699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com