我有 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;
}
错误:
An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in 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;
}
最佳答案
(int i = 6; in[i] != '/'; i++)
{
compare += in[i];
}
你是这个意思吗?
for (int i = 6; in[i] != '/'; i++)
{
compare += in[i];
}
目前,您的字符串中没有七个字符,因此您的compare
无效。事实上,在任何情况下您都需要在那里添加一些边界检查。
此外,异常文本暗示您实际上是在编写 C++/CLI,而不是 C++。我说得对吗?
关于C++ 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7507184/