Lab 09@cs 121
Lab 09@cs 121
FUNDAMENTALS OF PROGRAMMING
LAB 09 – Strings
Saif Hassan
Date: 27 th October, 2019
READ IT FIRST
Prior to start solving the problems in this assignments, please give full
concentration on following points.
5. HOW TO SUBMIT – rename all .cpp files as task number and make .zip
file, name it as 000-00-0000_lab09.zip, and submit .cpp file ONLY.
2. It is not bad if you keep your code indented inside the loops, if and
else blocks as well.
Practice
Following code is given for sample code for string and its functions.
1. #include <iostream>
2. #include <string>
3. #include <cstdlib>
4.
5. using namespace std ;
6.
7. int main ()
8. {
9. // creating string variable
10. string a = "22345";
11. char b[] = "a2345";
12.
13. // getting string input friom user
14. getline(cin, a);
15.
16. // calculating size of string
17. cout<<strlen(b)<<endl; // strlen is used for char array
18. cout<<a.size()<<endl; // size used with string var
19. cout<<a.length()<<endl; // size used with string var
20.
21. // using substr function
22. string s = a.substr(0,2);
23. cout<<s<<endl;
24.
25. // conversion from string to int
26. int c = atoi(a.c_str());
27.
28. // isalpha used for checking whether it is abc or not
29. cout<<isalpha(b[0]);
30.
31. // replace str2 with C in str1
32. string str1 = "This is C language";
33. string str2 = "C++";
34. str1.replace(8,1,str2);
35.
36. cout<<endl;
37. system ("PAUSE") ;
38. return 0 ;
39. }
Page 2 of 4
Lab08 – Functions CS121 Fundamentals of Programming Instructor: Saif Hassan
Exercises
Task01 (string without loop)
Modify task01 and do each task with loop. Use strlen(string) with char[]
or use size() or length() with string var function to calculate length
of string.
a) Input date (28/10/2019) in string and separate day, month and year
in integer type.
b) Input student id (021-12-0006) and tell student’s department and
enrolled year.
c) Input phone number (0300-1234567) and tell the network, user is
using.
Task04 (Concatenation)
Ask user two inputs firstname and lastname and perform following tasks:
Task05 (Comparison)
Page 3 of 4
Lab08 – Functions CS121 Fundamentals of Programming Instructor: Saif Hassan
Write a code to check whether two words are similar or not. Use strcmp
function.
Task06 (Sentence)
Page 4 of 4