Sei sulla pagina 1di 9

Capital University of Science and Technology Islamabad

Department of Computer Science,


Faculty of Computing

Lab 12: Manipulating Sequence of Characters using C++


“string” Data-type
Lab 12: Manipulating Sequence of Characters using C++ “string” data-type.

Table of Contents
1. Introduction 124

2. Activity Time-boxing 124

3. Objective of the Experiment 124

4. Concept Map 125


4.1 String manipulation using specialized data-type 125

5. Home work before Lab 125


5.1 Problem Solution Modeling 125
5.2 Practices from home 126

6. Procedure & Tools 126


6.1 Tools 126
6.2 Setting-up Visual Studio 2008 126
6.3 Walkthrough Task 126

7. Practice Tasks 128


7.1 Practice Task 1 128
7.2 Practice Task 2 128
7.3 Out comes 129
7.4 Testing 129

8. Evaluation Task (Unseen) 129

9. Evaluation Criteria 129

10. Further Readings 130


10.1 Strings Tutorial 130
10.2 Slides 130

Appendix A – Basic String Functions 130

Department of Computer Science, P a g e | 123


CUST, 2018
Lab 12: Manipulating Sequence of Characters using C++ “string” data-type.

Lab 12: Manipulating Sequence of Characters using


C++ “string” Data-type
1. Introduction

In the Lab-7, you have already learned how to deal with data consisting of sequence of characters (text).
Sequence of characters can be manipulated using character arrays (char [ ]). Actually, character array is
the way C language deals with the text data; therefore it is also called “C-String”.

The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to
work on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of
section 8, your lab instructor will give you some tasks at runtime and will evaluate those according to
the criteria mentioned in section 9. Section 10 lists some further reading links.

Note: Before coming to the lab, you are required to read Lab contents until section 5. You will
start your practical work from section 6 onward in the lab.

Relevant Lecture Readings:

a) Lecture No. 21
b) Text Book: Computer Programming by D.S. Malik, second edition, pages: 446—472

2. Activity Time-boxing

Table 1: Activity Time Boxing


Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20 mins 20 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Specialized Tasks 30 mins 30 mins
7 Practice tasks 30 mins for each task 60 mins
8 Evaluation Task 55 mins for all assigned task 55 mins
Total Time 170 mins

3. Objective of the Experiment


 To get basic understanding of string data-type.
 To get familiarize and practice basic string functions.

Department of Computer Science, P a g e | 124


CUST, 2018
Lab 12: Manipulating Sequence of Characters using C++ “string” data-type.

4. Concept Map
To deal with sequence of characters, C++ provides its own specialized data-type based on string class. In
C++, std::string is the standard way to deal with the sequence of characters. A string variable can store
sequence of characters, letters, symbols (*, $, %), and non-keyboard characters such as escape
sequences [Lab-1]. Some of the examples of text that a string variable can store are: “Hello”,
“BC050102”, “I Love C++ Programming!”, “Grade:\n\tA”.

The string data-type provides many built-in functions to ease the tasks related to text manipulation.
Some of the example tasks which can be performed using built-in string functions are: text comparison,
combining two text values (concatenation), finding occurrence of some character or sequence of
characters in a text, and replacing/erasing some parts of the text. The ‘Appendix A’ shows some of the
most used string functions along their parameter specification/meaning. String is not the built-in data
type rather it is part of the C++ standard library. Therefore, to use string types you have to include the
corresponding library in the program using include statement:

#include <string>

4.1 String manipulation using specialized data-type


C/C++ provides character data-type to deal with individual character values. In C, character arrays are
used to deal with more than one characters or text. This character array is often referred as C-String.

C++ provides a specialized data-type (called string) to handle or manipulate text. A string type variable
can store same information but provides many useful methods/functions to process the text. C++’s
string type has several other advantages too over C-String (character array) as discussed below:

4.1.1 Memory Storage


One of the main drawbacks of using character array is that it has fixed size in memory, whether or not
you utilize full allocated space. For example: if you create a character array based on 80 elements
(characters), in memory 80 bytes will be reserved for it. If you store “Pakistan” in this character array
only 9 array elements (including ‘\0’ or null character) will be utilize, other 71 bytes will remain allocated
but un-utilized. Strings have variable sizes and the amount of space they take up in memory depends on
the length of the string.

4.1.2 String Functions


C++ string type provides many built-in functions to ease text handling. That’s why using string type
instead of character arrays will ease writing programs in less time and with shorter source code.
Furthermore, you do not have to implement major text manipulation functionalities by yourself. In
“Appendix A” list of basic string functions is provided.

5. Home work before Lab

5.1 Problem Solution Modeling


Write the pseudo-code of the following task. You are required to bring this code with you and submit
to your lab instructor.

5.1.1 Problem description: Write pseudo-code of program that finds number of occurrences of a string
Department of Computer Science, P a g e | 125
CUST, 2018
Lab 12: Manipulating Sequence of Characters using C++ “string” data-type.

(based on at-least two characters) in another string (for example a sentence). The program should get
input in a string “str1” representing a sentence (terminated by”.”). Then, it should ask the user to enter
another string “str2”. In the end program should display the count or number representing total
occurrences of “str2” in “str1”.

5.2 Practices from home


5.3.1 Task-1
Write a C++ program that asks the user to enter a string. The program should count total number of
vowels in the input string. The output of the program should report vowel count for each vowel
character (a, e, i, o , u), and total or sum of all vowel count.
Sample Input:
Please enter a string: i love C++ programming!

Sample Output:
Total Vowels: 6
A: 1
E: 1
I: 2
O: 2
U: 0

5.3.2 Task-2
Write a C++ program that asks the user to enter a string. After that, the program should ask for another
string in a variable named “str_new”. Take another string input in the variable named “str_old”. In the
end, the program should replace the “str_new” with “str_old”. In the end the program prints the update
string.

Sample Input:
Please enter a string: Java programming is a great fun!
Enter word to replace: Java
Enter word to replace with: C++

Sample Output:
C++ programming is a great fun!

6. Procedure & Tools

6.1 Tools
Visual Studio 2008.

6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]


Setup Visual Studio and make a project named “WordCounter”. For setup details please refer to the Lab-
1 section 6.2.

6.3 Walkthrough Task [Expected time = 30 mins]


Write a C++ program that counts total words in a sentence. First, get input in a string variable “prg” for a
Department of Computer Science, P a g e | 126
CUST, 2018
Lab 12: Manipulating Sequence of Characters using C++ “string” data-type.

paragraph (terminated by enter key). Your program should count total number of words in the
paragraph (using find function of string) and print that value on screen as follows:
You entered 20 words for the paragraph.

To achieve such output, you need to follow the following instructions.

6.3.1 Writing Code


In the source file created in the project “WordCounter” write following C++ code:

.Figure 1: C++ code for word counter program

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2)

6.3.3 Executing the Program


A sample output after running the program is shown below:

Figure 2: Final output of word count program


Department of Computer Science, P a g e | 127
CUST, 2018
Lab 12: Manipulating Sequence of Characters using C++ “string” data-type.

7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the folder specified by the
lab instructor.

7.1 Practice Task 1 [Expected time = 30 mins]


Write a C++ program that asks the user to enter a string value in a variable named “Str”. The input string
should be of size 20 characters (minimum). Next, apply following operation (in sequence) on the input
string:
1) Find and print the length of the string.
2) Display string in reverse order.
3) Concatenate “Hello World” to the string.
4) Count number of words in updated string.
5) Convert whole string in lowercase.

Sample Inputs:
My name is Ali Raza

Sample Outputs:
1) String length: 19
2) azaR ilA si eman yM
3) My name is Ali Raza Hello World
4) 7
5) my name is ali raza hello world

7.2 Practice Task 2 [Expected time = 30 mins]


Write a C++ program which repeatedly asks the user to enter their contact numbers. Create a string
variable named “Phone_No” and take the input in the following pattern: “+92423672123” where the
first three characters represent country code (e.g., +92 as shown in the example pattern), next two
characters (e.g., 42 according the shown example number) represent the city code, while next 7
characters represent the actual number.
Your task is to display appropriate messages for the numbers belonging to three cities: Islamabad
(having city code 51), Lahore (city code 42), and Karachi (city code: 21). Any number having different
country code or city code must be reported as “Un-known number“. Please also ensure that the user
must enter the number according to the shown pattern only and the size of the input string must be 12
characters.

Sample Inputs:
Enter a number: +92214352682

Sample Outputs:
This number belongs to Karachi
Do you want to enter another number (y/n): n
End of program. Bye!

Department of Computer Science, P a g e | 128


CUST, 2018
Lab 12: Manipulating Sequence of Characters using C++ “string” data-type.

7.3 Out comes


After completing this lab, student will be able to use string data type and its function for text
manipulation.

7.4 Testing
Test Cases for Practice Task-1
Sample Input-1 Y<X is the same as X>= Y
Output-A Length: 26
Output-B Y=>X sa emas eht si X<Y
Output-C Y < X is the same as X>= Y Hello World
Output-D 6
Output-E Y<x is the same as x>=y

Test Cases for Practice Task-2


Sample Input Sample Output Remarks
+9251111878787 Unknown Number Number is over 12 characters
+92333540061 Unknown Number Unknown city code
-92515254722 Unknown Number Wrong country code format
+43515254722 Unknown Number Unknown country code
+92515254722 This number belongs to Islamabad -
+92423454211 This number belongs to Lahore -
+92218123319 This number belongs to Lahore -

Practice Tasks Confirmation


T1
T2

8. Evaluation Task (Unseen) [Expected time = 55 mins]


The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student
has finished the complete/partial task(s).

Table 2: Evaluation of the Lab


Sr. No. Task No Description Marks

Department of Computer Science, P a g e | 129


CUST, 2018
Lab 12: Manipulating Sequence of Characters using C++ “string” data-type.

1 4.1 Problem Modeling 20


2 6 Procedures and Tools 10
3 7.1 and 7.2 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Readings

10.1 Strings Tutorial


A comprehensive list of string functions can be found at
http://www.prismnet.com/~mcmahon/Notes/strings

10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

Appendix A – Basic String Functions


String Functions Description
size( ) Returns the length of the string
length( ) Returns the length of the string (same as size( ) function)
clear( ) Delete the contents of the string. Reset it to an empty string
empty( ) Return true if the string is currently empty, false otherwise
at (X) Return the character at position X (integer) in the string. Similar to using the [ ]
operator
substr(X, Y) Returns a copy of the substring (i.e. portion of the original string) that starts at index
X and is Y characters long. Both X and Y are integers.
substr(X) Returns a copy of the substring, starting at index X of the original string and going to
the end
append(str2) Appends str2 (a string or a c-string) to the calling string
str1.compare(str2) Performs a comparison. A negative value return means str1 comes first. Positive
means str2 comes first. 0 means both strings are same.
str.find(str2, X) Returns the first position at or beyond position X (integer value), where the string str2
is found inside of str sting variable.
str.find(CH, X) Returns the first position at or beyond position X where the CH (a character variable)
is found in str

str.insert(X, CH) Inserts the character CH into string str starting at position X (integer value).
replace(X, N, str) Replace N number of characters in the calling string, with value of “str” string variable
starting at position X (integer value).

Department of Computer Science, P a g e | 130


CUST, 2018

Potrebbero piacerti anche