Accept two strings using character arrays. Use string functions `strcpy()`, `strcat()`, `strcmp()`, and `strlen()` to perform various operations.

SOLUTION....

C++ String Functions Example

#include <iostream>
#include <cstring>   // for string functions
using namespace std;

int main() {
    char str1[100], str2[100], str3[100];

    // Input two strings
    cout << "Enter first string: ";
    cin.getline(str1, 100);

    cout << "Enter second string: ";
    cin.getline(str2, 100);

    // 1. Copy string using strcpy
    strcpy(str3, str1);
    cout << "\nAfter strcpy, copied str1 into str3: " << str3 << endl;

    // 2. Concatenate strings using strcat
    strcat(str1, str2);
    cout << "After strcat, concatenation of str1 and str2: " << str1 << endl;

    // 3. Compare strings using strcmp
    int cmp = strcmp(str3, str2);
    if (cmp == 0)
        cout << "str3 and str2 are equal" << endl;
    else if (cmp > 0)
        cout << "str3 is greater than str2" << endl;
    else
        cout << "str3 is smaller than str2" << endl;

    // 4. Find string length using strlen
    cout << "Length of str2 = " << strlen(str2) << endl;

    return 0;
}
    

OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *