我有2个字符串:in
,其中包含用户最初输入的链接(假设为“http://google.com/test”),以及found
,其中包含已被本计划的其他部分发现。
此功能的目标是比较http://
和/test
之间的字符串部分,即:“google.com”
我遇到的问题是循环没有添加到比较字符串,因此后来尝试在运行时比较程序中的2个字符串。
bool isLinkExternal(string in, string found)
{
string compare = "";
bool isExternal = false;
//Get domain of original link
for (int i = 6; in[i] != '/'; i++)
{
compare += in[i];
}
system("pause");
//Compare domains of original and found links
if (found.compare(7,compare.length(),compare) != 0)
isExternal = true;
return isExternal;
}
错误:
未处理的类型异常 发生'System.Runtime.InteropServices.SEHException' ParseLinks.exe
它指向的代码行:
if (found.compare(7,compare.length(),compare) == 0)
固定代码(工作):
bool isLinkExternal(string in, string found)
{
const int len = found.length();
int slashcount = 0;
string comp;
//Parse found link
for (int i = 0; i != len; i++)
{
//Increment when slash found
if (found[i] == '/')
{
slashcount++;
}
if (slashcount < 3)
{
comp += found[i];
}
}
//Compare domains of original and found links
if (in.compare(0,comp.length(),comp) == 0)
return false;
else
return true;
}
答案 0 :(得分:4)
(int i = 6; in[i] != '/'; i++)
{
compare += in[i];
}
你的意思是?
for (int i = 6; in[i] != '/'; i++)
{
compare += in[i];
}
目前,您的字符串中没有七个字符,因此您的compare
无效。实际上,在任何情况下都需要添加一些检查边界。
此外,异常文本暗示您实际上是在编写C ++ / CLI,而不是C ++。我是对的吗?
答案 1 :(得分:0)
这是否更好:
for (int i = 7; in[i] != '/'; i++)
{
compare += in[i];
}