두 개의 문자열이 주어지면 두 문자열이 같은지 여부를 확인하는 방법입니다.
예:
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>
이 문제는 다음 두 가지 방법 중 하나를 사용하여 해결할 수 있습니다.
- 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)> >cout << s1 <<>' is greater than '> << 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은 문자열의 길이입니다.
모의 추상 클래스를 주입하는 방법
이는 문자열이 함수에 전달되면 스택에 자체 복사본이 생성되기 때문입니다.
- 표준:: 비교()
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)> >cout << s1> ><<>' is greater than '> ><< 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;> }> |
>
SQL 날짜별 주문
>산출
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++ 관계 연산자와 비교()의 차이점 :-
- 비교()는 int를 반환하는 반면 관계 연산자는 부울 값, 즉 true 또는 false를 반환합니다.
- 단일 관계형 연산자는 특정 작업에 고유한 반면, 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';> 위의 예는 방법을 명확하게 보여줍니다. 비교하다() 추가 처리량이 많이 줄어들므로 특정 위치에서 하위 문자열 비교를 수행하는 동안 사용하는 것이 좋습니다. 그렇지 않으면 둘 다 거의 동일한 방식으로 수행됩니다.