C++ Strings: C++ String Compare Example
C++ Strings: C++ String Compare Example
In C++, string is an object of std::string class that represents sequence of Let's see the simple example of string comparison using strcmp() function.
characters. We can perform many operations on strings such as
concatenation, comparison, conversion etc. 1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main ()
5. {
Output: Output:
1. #include <iostream> 1. #include <iostream>
2. #include <cstring> 2. #include <cstring>
3. using namespace std; 3. using namespace std;
4. int main() 4. int main()
5. { 5. {
6. char key[25], buffer[25]; 6. char key[25], buffer[25];
7. cout << "Enter the key string: "; 7. cout << "Enter the key string: ";
8. cin.getline(key, 25); 8. cin.getline(key, 25);
9. cout << "Enter the buffer string: "; 9. strcpy(buffer, key);
10. cin.getline(buffer, 25); 10. cout << "Key = "<< key << endl;
11. strcat(key, buffer); 11. cout << "Buffer = "<< buffer<<endl;
12. cout << "Key = " << key << endl; 12. return 0;
13. cout << "Buffer = " << buffer<<endl; 13. }
14. return 0; 1. #include <iostream>
15. } 2. #include <cstring>
1. #include <iostream> 3. using namespace std;
2. #include <cstring> 4. int main()
3. using namespace std; 5. {
4. int main() 6. char key[25], buffer[25];
5. { 7. cout << "Enter the key string: ";
6. char key[25], buffer[25]; 8. cin.getline(key, 25);
7. cout << "Enter the key string: "; 9. strcpy(buffer, key);
8. cin.getline(key, 25); 10. cout << "Key = "<< key << endl;
9. cout << "Enter the buffer string: "; 11. cout << "Buffer = "<< buffer<<endl;
10. cin.getline(buffer, 25); 12. return 0;
11. strcat(key, buffer); 13. }
12. cout << "Key = " << key << endl;
13. cout << "Buffer = " << buffer<<endl; Output:
14. return 0;
15. } Enter the key string: C++ Tutorial
Key = C++ Tutorial
Buffer = C++ Tutorial
Output:
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char ary[] = "Welcome to C++ Programming";
7. cout << "Length of String = " << strlen(ary)<<endl;
8. return 0;
9. }
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char ary[] = "Welcome to C++ Programming";
7. cout << "Length of String = " << strlen(ary)<<endl;
8. return 0;
9. }
Output:
Length of String = 26