繁体   English   中英

C ++字符串比较

[英]C++ String Compare

我有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;
}

错误:

ParseLinks.exe中发生了未处理的“System.Runtime.InteropServices.SEHException”类型异常

它指向的代码行:

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 ++。 我对吗?

这是否更好:

for (int i = 7; in[i] != '/'; i++)
{
compare += in[i];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM