C++ で 2 つの文字列を比較する
2 つの文字列が与えられた場合、2 つの文字列が等しいかどうかを確認する方法。
例:
Input : ABCD, XYZ Output : ABCD is not equal to XYZ XYZ is greater than ABCD Input : Geeks, forGeeks Output : Geeks is not equal to forGeeks forGeeks is greater than Geeks
この問題は、次の 2 つの方法のいずれかを使用して解決できます。
- C++ 関係演算子
CPP
// CPP code to implement relational> // operators on string objects> #include> using> namespace> std;> void> relationalOperation(string s1, string s2)> {> > if> (s1 != s2)> > {> > cout < < s1 < <> ' is not equal to '> < < s2 < < endl;> > if> (s1>s2)>>' < < s2 < < endl;> > else> > cout < < s2 < <> ' is greater than '> < < s1 < < endl;> > }> > else> > cout < < s1 < <> ' is equal to '> < < s2 < < endl;> }> // Driver code> int> main()> {> > string s1(> 'Geeks'> );> > string s2(> 'forGeeks'> );> > relationalOperation(s1, s2);> > string s3(> 'Geeks'> );> > string s4(> 'Geeks'> );> > relationalOperation(s3, s4);> > return> 0;> }> |
出力
Geeks is not equal to forGeeks forGeeks is greater than Geeks Geeks is equal to Geeks
時間計算量: O(min(n,m)) ここで、n と m は文字列の長さです。
補助スペース: O(max(n,m)) ここで、n と m は文字列の長さです。
これは、文字列が関数に渡されると、それ自体のコピーがスタックに作成されるためです。
- std::比較()
CPP
// CPP code perform relational> // operation using compare function> #include> using> namespace> std;> void> compareFunction(string s1, string s2)> {> > // comparing both using inbuilt function> > int> x = s1.compare(s2);> > if> (x != 0) {> > cout < < s1> > < <> ' is not equal to '> > < < s2 < < endl;> > if> (x>0)>> > < < s2 < < endl;> > else> > cout < < s2> > < <> ' is greater than '> > < < s1 < < endl;> > }> > else> > cout < < s1 < <> ' is equal to '> < < s2 < < endl;> }> // Driver Code> int> main()> {> > string s1(> 'Geeks'> );> > string s2(> 'forGeeks'> );> > compareFunction(s1, s2);> > string s3(> 'Geeks'> );> > string s4(> 'Geeks'> );> > compareFunction(s3, s4);> > return> 0;> }> |
出力
Geeks is not equal to forGeeks forGeeks is greater than Geeks Geeks is equal to Geeks
時間計算量: O(min(n,m)) ここで、n と m は文字列の長さです。
補助スペース: O(max(n,m)) ここで、n と m は文字列の長さです。
これは、文字列が関数に渡されると、それ自体のコピーがスタックに作成されるためです。
C++ 関係演算子と Compare() の違い:-
- Compare() は int を返しますが、関係演算子はブール値、つまり true または false を返します。
- 単一のリレーショナル演算子は特定の操作に固有ですが、compare() は渡された引数のタイプに基づいて、多くの異なる操作を単独で実行できます。
- Compare() を使用すると、指定された文字列内の任意の位置にある任意の部分文字列を比較できます。そうでない場合は、関係演算子を使用して比較する文字列を単語ごとに抽出するという長い手順が必要になります。
例:-
- Compare() の使用
// Compare 3 characters from 3rd position // (or index 2) of str1 with 3 characters // from 4th position of str2. if (str1.compare(2, 3, str2, 3, 3) == 0) cout < <'Equal'; else cout < <'Not equal';
- 関係演算子の使用
for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++) { if (s1[i] != s2[j]) break; } if (i == 6 && j == 7) cout < < 'Equal'; else cout < < 'Not equal'; 上の例は、その方法を明確に示しています。 比較する() 多くの余分な処理が削減されるため、ある位置で部分文字列の比較を実行するときにこれを使用することをお勧めします。それ以外の場合は、どちらもほぼ同じように実行されます。