【问题标题】:String compare against an element in a string vector in C++ [duplicate]字符串与C++中字符串向量中的元素进行比较[重复]
【发布时间】:2013-08-17 03:51:51
【问题描述】:

我正在尝试将字符串(忽略大小写)与向量字符串中的指定元素进行比较(我不想查看字符串是否存在于向量中的任何位置,仅当它存在于特定索引处时)。

我没有像往常一样成功地使用字符串比较。任何帮助将不胜感激。

【问题讨论】:

  • 显示你尝试过的和得到的结果。

标签: c++ string vector compare


【解决方案1】:

strnicmp( ... ) 是您的工具。 'n' 用于限制长度,'i' 用于不区分大小写。你只需要将具体的索引添加到向量中:vector+pos&vector[pos]

int isKeyFoundAtPos( const char* key, const char* vector, int vPos) {

    if( vPos > strlen(vector) )  // if you want to be safe, check for this and deal with it.
        return -1;

    return 0 == strnicmp( key, vector+vPos, strlen(key) );
}

...

const char* myKey = "abc";
const char* myVector = "123abc456ABC";

isKeyFoundAtPos( myKey, MyVector, 3 ); // string found
isKeyFoundAtPos( myKey, MyVector, 9 ); // string also found

我编写了包装程序作为示例,但老实说,我会直接使用strnicmp()

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 2021-07-10
    • 2021-09-06
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多