std::string str1("green apple"); std::string str2("red apple");//1.str1和str2比较:参数形式1if(str1.compare(str2) !=0) std::cout << str1 <<" is not "<< str2 <<'\n';//2.str1的下标6开始的5个字符和"apple"比较:参数形式5if(str1.compare(6,5,"apple") ==0) std::c...
// CPP code to demonstrate// int string::compare(size_type idx, size_type len,// const string& str) const#include<iostream>usingnamespacestd;voidcompareOperation(strings1,strings2){// Compares 5 characters from index number 3 of s2 with s1if((s2.compare(3,5, s1)) ==0)cout<<"Here,...
// CPP code to perform comparison using compare()#include<iostream>usingnamespacestd;voidusingCompare(string str1,string str2){// Direct Comparisonif(str1.compare(2,3,str2,3,3)==0)cout<<"Both are same";elsecout<<"Not equal";}// Main functionintmain(){strings1("GeeksforGeeks...
第二个就是这篇在stackoverflow上的文章 https://stackoverflow.com/questions/198431/how-do-you-co...
如 str1.compare(pos1, len1, str2, pos2, len2)。 与C风格字符串比较:虽然不常见,但 compare 函数也允许与C风格的字符串(即字符数组)进行比较。 示例代码 下面是一个使用 string 的compare 函数进行字符串比较的示例代码: cpp #include <iostream> #include <string> int main() { std...
另一个功能强大的比较函数是成员函数compare()。他支持多参数处理,支持用索引值和长度定位子串来进行比较。他返回一个整数来表示比较结果,返回值意义如下:0-相等 〉0-大于 <0-小于。举例如下: string字符串使用方法都类似strings("abcd"); s.compare("abcd");//返回0s.compare("dcba");//返回一个小于0的值...
例子1 #include<iostream>usingnamespacestd;voidmain(){stringstr1="Hello";stringstr2="javatpoint";intk= str1.compare(str2);if(k==0)cout<<"Both the strings are equal";elsecout<<"Both the strings are unequal"; } 输出: Both the strings are unequal ...
https://en.cppreference.com/w/cpp/string/basic_string/compare Jan 4, 2022 at 6:15pm seeplus(6597) Just for info. .compare() is similar to the c function strcmp() where the result is either < 0 (less than), - (equal), > 0 (greater). ...
compare(str2) << std::endl; std::cout << str1.compare("apple") << std::endl; return 0; } Output-1 0 ExplanationAt first, since 'a' (ASCII 97) is less than 'b' (ASCII 98) so output is a negative number (-1). In the second, the output is 0 as values stored in str1...
cout << "A.compare(2, 3, B, 2, 3):" << A.compare(2, 3, B, 2, 3) << endl; // 结果:0 // 由结果看出来:0表示下标,3表示长度 // "123" 和 "123"比较 cout << "C.compare(0, 3, D, 0, 3)" <<C.compare(0, 3, D, 0, 3) << endl; // 结果:0 ...