You are on page 1of 7

Name: Muhammad Kaif Roll#:02-235222-013

Assignment
CP LAB # 11

Task 1:
Write a program that determines if a string contains a certain alphabet and its number of
occurrences. It displays ‘Not Found’ if the letter is not found in the string. Be sure to take case of
the case sensitiveness.
For example:
Enter string: Tooba
Enter letter to search: o
Found! Occurred 2 times in the string

Screenshot
Name: Muhammad Kaif Roll#:02-235222-013

Code

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main () {
int count = 0;
string text;
string letter;
cout << "Enter any text: ";
getline(cin, text);
int size = text.size();
cout << "Enter letter you want to search in the given text: ";
cin >> letter;
int index = text.find(letter);
cout << "Searched letter is found at ";
for(int i = 0; i <size;i++) {
if(text[index] == text[i]) {
count++;
cout << i << " ";
}
}
cout << "index" << endl;
cout << "Occured " << count << " times." << endl;
}
Name: Muhammad Kaif Roll#:02-235222-013

Task 2:
Write a program that compare two strings and prints the shorter one. It prints equal if both
strings are same.

Screenshot

Code
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main () {
Name: Muhammad Kaif Roll#:02-235222-013

string str1="Kaif";
string str2="Zonish";
int str_one_size=str1.size();
int str_two_size=str2.size();
if(str_one_size < str_two_size) {
cout << "String 1 is smaller than String 2" << endl;
}
else if(str_two_size < str_one_size) {
cout << "String 2 is smaller than String 1" << endl;
}
else if(str_one_size == str_two_size) {
cout << "Both strings are equal" << endl;
}
else {
cout << "\0";
}
}

Task 3:
Name: Muhammad Kaif Roll#:02-235222-013

Write a program that takes a string as an input and copies it another empty string and displays
it.

Screenshot

Code
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main () {
string str1="Hello World";
string str2;
str2=str1;
cout << str2 <<endl;
Name: Muhammad Kaif Roll#:02-235222-013

Task 4:
Write a program to print the first and last characters of a string.

Screenshot

Code
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main () {
string str1="Hello World";
cout << "First character is " << str1.front() << endl;
Name: Muhammad Kaif Roll#:02-235222-013

cout << "Last character is " << str1.back() << endl;


}

You might also like