我创建了一个在某种程度上应该表现得像 std::string 的类。我测试过的所有功能似乎都可以正常工作,但我正在创建一个 justify 方法,该方法应该在已经存在的空白点中向字符串添加空格。方法比较简单:
String String::justify(const int Width) const
{
String result = *this;
int i = 0;
if(nextBlank(0) == -1 || length() > Width)
return *this;
while(result.length() < Width)
{
i = result.nextBlank(i);
if(i == -1) result.nextBlank(0);
result = result.substr(0,i) + ' ' + result.substr(i + 1, result.length());
i = result.nextNonBlank(i);
}
return result;
}
当调用此方法时,我通常会得到一个奇怪的混合字符,因为我认为它会在某处超过 Null 终止字符,但我不知道在哪里或为什么,这就是我希望你们能帮助我的.我相信它与 substr 方法有关,因为那是它输出奇怪的时候。即使不在 justify 函数中,如果 substr 被调用两次,输出也会不正确,但调用一次它会正常工作。
此外,这里还有 nextNonBlank、nextBlank 和 substr 函数,因为它们是相关的:
int String::nextBlank(const int Index) const
{
int i = Index;
while(i <= length())
{
if(S[i] == ' ' && (i != Index || S[0] == ' '))
{
return i;
}
else if(i == length())
return -1;
++i;
}
return -1;
}
int String::nextNonBlank(const int Index) const
{
int i = Index;
while(i <= length())
{
if(S[i] != ' ' && i != Index )
{
return i;
}
++i;
}
return -1;
}
String String::substr(int Start, int End) const
{
String result;
assert(End <= length());
for(int i = Start; i <= End; ++i)
result = result + S[i];
return result;
}
如果你们认为这可能是构造函数或其他问题,则完整代码已发布在这里:http://pastebin.com/mTakMPtq
如果有人能花时间看看这个,我将不胜感激。我坚持这个的时间比我愿意承认的要长。
这是一个示例测试:
int main()
{
String str("Here is a string.");
std::cout << "Without justify:" << std::endl;
str = str.substr(0, 3) + " " + str.substr(3 + 1, str.length());
std::cout << str << "\n\n";
std::cout << "With justify:" << std::endl;
std::cout << str.justify(25);
}
这是输出:
Without justify: ÐC*Here is a string.
With justify: ÐC*ÐC*Here ÐC* is a string.
最佳答案
您的 substr()
函数有问题。添加了一些用于调试的变量并使用 2 个不同的字符串运行。这是每个的第一次迭代:
while(result.length() < Width)
{
i = result.nextBlank(i);
String temp1 = result.substr(0,i);
String temp2 = " ";
String temp3 = result.substr(i + 1, result.length());
int tmpint = result.length();
result = result.substr(0,i) + " " +result.substr(i + 1, result.length());
i = result.nextNonBlank(i);
}
i: 1 tmpint: 34 result: 0x603450 "A string without a beginning space" tmp1: 0x6038b0 " with beginning space\021\001A " tmp2: 0x603670 " " tmp3: 0x603ad0 "x¦[÷ÿ\177string without a beginning space" i: 0 tmpint: 24 result: 0x603450 " with beginning space" tmp1: 0x6038b0 "x¦[÷ÿ\177x¦[÷ÿ\177x¦[÷ÿ\177x¦[÷ÿ\177\021\001 " tmp2: 0x603690 " " tmp3: 0x603ad0 " with beginning space"
关于c++ - 多次调用方法时出现奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22394360/