有没有一个函数可以比较从参数化点a到点B的两个字符串

Is there a function to compare two strings from a parameterized point A to point B

本文关键字:到点 字符串 两个 函数 有一个 比较 参数      更新时间:2023-10-16

我想知道,如果给定:

string name_a;
string name_b;

会有一些已经存在的函数允许我比较两个字符串的特定数量的字符,如strncmp(),但来自我的string中的特定索引。

例如:

int main(){
    string name_a = "Morning";
    string name_b = "Burning";
    if(FUNCTION(name_a.c_str(),name_b.c_str(), NUMBER_OF_CHAR_COMPARED, INDEX_FIRST_CHAR) == 0 ){
        cout << "Same literal" << endl;
    }
    return 0; 
}

std::string成员函数compare有一个包含所需参数的版本:

int compare (size_t pos, size_t len, const string& str) const;

它从pos开始比较,最多使用len个字符,因此您可以使用

if (name_a.compare(INDEX_FIRST_CHAR, NUMBER_OF_CHAR_COMPARED, name_b) == 0)

您可以使用substrcompare方法

if(name_a.substr(INDEX_FIRST_CHAR, NUMBER_OF_CHAR_COMPARED).compare( name_b.substr(INDEX_FIRST_CHAR, NUMBER_OF_CHAR_COMPARED) ) == 0)

它是strncmp(和c字符串偏移量):

strncmp(&name_a.c_str()[index_first], &name_b.c_str()[index_first], length);