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

错误:

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/

相关文章:

c++ - 插入二叉树(不是 BST)不起作用

c++ - qt中线程的使用方法

Javascript,没有三元运算符的字符串连接

c# - 将整数转换为字符串?

c++ - 如何检查是否已准备好从 windows 套接字读取超过 1 个字节?

c++ - 我如何检测 CDRom 是否是 Linux 上的 DVD

string - Dart:在赋值中使用 * 运算符时会分配多少个字符串对象?

python - 使用 Python 查找两个文本文件的段落中的重复关键字,并在新的文本文件中列出结果(比较它们)

c# - .Net 中的字符串比较 : "+" vs "-"

java - 检查静态数组 : Java 中是否存在值