0% found this document useful (0 votes)
6 views3 pages

String Manipulation in C++

Uploaded by

mdnlopez
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

String Manipulation in C++

Uploaded by

mdnlopez
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <iostream>

#include <cstring>

using namespace std;

// Task 1: Concatenate two strings


void concatenateStrings() {
char str1[100], str2[100];
cout << "Enter the first string: ";
[Link](str1, 100);
cout << "Enter the second string: ";
[Link](str2, 100);
strcat(str1, str2);
cout << "Concatenated string: " << str1 << endl;
}

// Task 2: Copy one string into another


void copyStrings() {
char source[100], destination[100];
cout << "Enter the source string: ";
[Link](source, 100);
strcpy(destination, source);
cout << "Copied string: " << destination << endl;
}

// Task 3: Compare two strings


void compareStrings() {
char str1[100], str2[100];
cout << "Enter the first string: ";
[Link](str1, 100);
cout << "Enter the second string: ";
[Link](str2, 100);

int result = strcmp(str1, str2);


if (result == 0) {
cout << "Strings are equal." << endl;
} else if (result < 0) {
cout << "First string is less than second string." << endl;
} else {
cout << "First string is greater than second string." << endl;
}
}

// Task 4: Find the length of a string


void findStringLength() {
char str[100];
cout << "Enter a string: ";
[Link](str, 100);
cout << "Length of the string: " << strlen(str) << endl;
}

// Task 5: Find the last occurrence of a character in a string


void findLastOccurrence() {
char str[100];
char ch;
cout << "Enter a string: ";
[Link](str, 100);
cout << "Enter character to find: ";
cin >> ch;

char* lastOccurrence = strrchr(str, ch);


if (lastOccurrence) {
cout << "Last occurrence of '" << ch << "' is at position: " << (lastOccurrence - str) << endl;
} else {
cout << "Character not found in the string." << endl;
}
}

int main() {
int choice;
do {
cout << "\nActivity Menu:\n";
cout << "1. Concatenate Strings\n";
cout << "2. Copy Strings\n";
cout << "3. Compare Strings\n";
cout << "4. Find String Length\n";
cout << "5. Find Last Occurrence of a Character\n";
cout << "6. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
[Link]();

switch (choice) {
case 1: concatenateStrings(); break;
case 2: copyStrings(); break;
case 3: compareStrings(); break;
case 4: findStringLength(); break;
case 5: findLastOccurrence(); break;
case 6: cout << "Exiting..." << endl; break;
default: cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 6);

return 0;
}

You might also like