C++:<=有符号和无符号之间的冲突

标签 c++ substring substr

我已经围绕 .substr 函数创建了一个包装器:

wstring MidEx(wstring u, long uStartBased1, long uLenBased1)
{
    //Extracts a substring. It is fail-safe. In case we read beyond the string, it will just read as much as it has
    // For example when we read from the word HELLO , and we read from position 4, len 5000, it will just return LO
    if (uStartBased1 > 0)
    {
       if (uStartBased1 <= u.size())
        {
            return u.substr(uStartBased1-1, uLenBased1);
        }
    }
    return wstring(L"");
}

它工作正常,但是编译器给我警告“<= 有符号和无符号之间的冲突”。

谁能告诉我如何正确地做到这一点?

非常感谢!

最佳答案

您应该使用wstring::size_type(或size_t)而不是long:

wstring MidEx(wstring u, wstring::size_type uStartBased1, wstring::size_type uLenBased1)
{
    //Extracts a substring. It is fail-safe. In case we read beyond the string, it will just read as much as it has
    // For example when we read from the word HELLO , and we read from position 4, len 5000, it will just return LO
    if (uStartBased1 > 0)
    {
       if (uStartBased1 <= u.size())
        {
            return u.substr(uStartBased1-1, uLenBased1);
        }
    }
    return wstring(L"");
}

这是 u.size() 的确切返回类型。这样,您可以确保比较给出预期的结果。

如果您正在使用 std::wstring 或其他标准库容器(如 std::vector 等),则 x::size_type 将被定义为 size_t。所以使用它会更加一致。

关于C++:<=有符号和无符号之间的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21350214/

相关文章:

sql - 如何在 Oracle SQL 中选择子字符串

c++ - 向列表中添加一个新元素,并返回对该元素的引用?

c++ - 将文件放在 Microsoft Visual Studio 中的什么位置以便自动找到它们?

c++ - 智能指针类的线程安全复制赋值运算符

C:评估字符串的一部分

java - 为什么这段代码不能正常工作?

javascript - 如果索引未知,如何在 javascript 中查找子字符串?

awk - 在固定宽度文件上使用 awk substr

Javascript 子字符串无法提取正确的数据

c++ - 这个指向成员转换的指​​针有什么问题?