Chapter 4 (Part II) - Array and Strings
Chapter 4 (Part II) - Array and Strings
Computer Programming
Chapter 4
Array and Strings
Chere L. (M.Tech)
Lecturer, SWEG, AASTU
Outline
Basic concepts of Array
Types of Array
One Dimensional Arrays
Multi-dimensional Arrays
Array declaration and initialization
Accessing and processing Array Elements
Basics of String
String declaration and initialization
String manipulation and operation
Input/output, Copying, Comparing, concatenation, etc.
String library functions and operators 2
Chapter 4
Part II
Array of Character
(Strings)
3
Chapter 4
4) Basic of String
What is string?
A string is a collection of characters .
It is usually a meaningful sequence representing the name of
an entity.
Generally it is combination of two or more characters
enclosed in double quotes.
Example:
“Good Morning” // string with 2 words
“Mehak” // string with one word
”B.P.” // string with letters and symbols
“” // an empty string
H i t h e r e ! \0
5
Chapter 4
4.1) String Declaration (C Style)
To declare a character array (string) the syntax is
char stringName[size]; //One dimensional string
char stringName[rSize] [cSize]; //Two dimensional string
rsize: no of strings
Example: char name[20]; cSize: size of each string
char stud_Name [30][20];
Note:
Here name and stud_name is a character array or string capable of
storing maximum of 19 characters and 570 characters respectively.
Since one character is reserved for storing ‘\0’, the number of elements
that can be stored in a 1D string is always size-1
Incase of 2D string each row should ends with ‘\0’ and the maximum
number of characters that will stored is total_size – row_Size
6
Chapter 4
4.1) String Declaration (C++ Style)
In C++ a string can be declared with string object in addition to that
of C-style declaration.
Example:
string myString;
string city, country; string address[10];
C-strings vs. string objects
C-strings string objects
Implemented as arrays of type char Instance of string class
Terminated with the null character Not terminated with null character
Compile-time allocation and run-time allocation and undetermined
determination of size size
Fixed size, but do not track their own Dynamic size and also track their own
size size
7
Chapter 4
4.1) String Declaration (C++ Style)
Unlike C-style string, the string class library used to declared a
string as regular variables (not as arrays), and they support:
The assignment operator =
Comparison operators ==, !=, etc
The + operator for concatenation
Type conversions from c-strings to string objects
A variety of other member functions
8
Chapter 4
4.2) String initialization
(a) 1D String Initialization
Example 1:
char name[20] = “John Eyob”;
null
string character
J o h n E y . . o b ‘\0
.............. .
name[7] name[9]
name[0] name[1]
- The above string will have 9 characters and 1 space for the null.
Thus size of name will be 10.
Example 2: string name = “John Eyob”;
9
Chapter 4
4.2) String initialization (cont’d)
Example 2: omitting string size
- Like as we do in array string size can be omitted also
char myAddress[] = “Addis Ababa, Ethiopia”;
In this case the string is initialized to the mentioned string literal and it’s
size is the number of characters in the string literal plus null character.
Here it is 20.
The null character is automatically inserted at the end of the string.
Example 3: initializing string character by character
char city [10] = {‘A’, ‘d’, ‘a’, ‘m’, ‘a’, ‘\0’};
char myCity [ ] = {‘D’, ‘i’, ‘r’, ‘e’, ‘d’, ‘e’, ‘w’, ‘a’, ‘\0’};
char company[10] =
E t h i o t e l ‘\0’
“Ethiotel”;
//invalid, string must enclosed within
char country [] = ‘Ethioipia’;
double quote
11
Chapter 4
4.2) String initialization (cont’d)
(b) Initializing 2 D Strings - 2D string can be initialize as follows
Example 1:
char word[4][5]={“Cat”, “Boat”, “Mat”,”Rate”};
12
4.2) String initialization (cont’d)
Example 2: Omitting string rowSize (number of strings)
char name[][12] = {"Mr. Biniam", "Mr. Abush",
“Miss Nardos", “Mrs. Kidest",
“Dr. Andualem", “Eng. Yodit"};
- #strings (rowSize) = 6
2nd index 1st
Columns index
0 1 2 3 4 5 6 7 8 9 10 11 12
M r . B i n i a m \0
5 4 3 2 1 0
M r . A b u s h \0
M i s s N a r d o s \0
rows
name[2][2] M r s . K i d e s t \0
D r . A n d u a l e m \0
E n g . Y o d i t \0
name[5][7] name[4][8] 13
4.2) String initialization (cont’d)
Example 3: initializing string objects
string address = “Addis Ababa”;
14
4.2) String initialization (cont’d)
Example 6: initializing string after declaration
char mystring [6];
mystring[0] = 'H'; mystring[1] = 'e';
mystring[2] = 'l'; mystring[3] = 'l';
mystring[4] = 'o'; mystring[5] = '\0';
Note: Like wise 2D strings can be initialized after declaration.
Note: it is no needed to use loop to input or display a string unless the character
array (string) is 2D and we need to read/print multiple strings.
17
Chapter 4
4.3) String input/output (cont’d)
18
Chapter 4
4.3) String input/output (cont’d)
Note:
The getline function continues to input the string until either the maximum
number of characters are input or it encounters the delimiter character
whichever comes first.
19
Chapter 4
4.4) String Operation/manipulations
Assignment/copy and comparison operation
In C-style, strings cannot be copied or compared using the
simple assignment or comparison operator as follow.
char str1[20], str2[20];
str2=str1; // Not allowed
if(str1==str2) //Not allowed
{ ….. }
However, using the C++ string objects the above two string
operations are valid
str2=str1; if(str1==str2) //both are valid
20
Chapter 4
4.4) String Operation/manipulations (cont’d)
Assignment/copy and comparison operation
In C-style, strings cannot be copied or compared using the
simple assignment or comparison operator as follow.
char str1[20], str2[20];
str2=str1; // Not allowed
if(str1==str2) //Not allowed
{ ….. }
However, using the C++ string objects the above two string
operations are valid
str2=str1; if(str1==str2) //both are valid
21
Chapter 4
4.4) String Operation/manipulations (cont’d)
Other string operations
Find the string length
Search string or substring
Characters case conversion
Reverse or swap string
Concatenating strings
String tokenization etc.
Modifying (replace) string
The above mentioned string manipulations can be performed
either through hard coding or using library functions
22
Chapter 4
4.4) String Manipulations and Library Functions
Here below list of string manipulation library functions
String
Function Description
operations
Copies string str2 (source string) into
strcpy(str1, str2); the character array str1 (destination
string). The value of str1 is returned.
String copying
Copies at most n characters of string
strncpy(str1, str2, size_t n); s2 into the array s1. The value of s1
is returned.
Appends string s2 to string s1. The
strcat (str1, str2);
value of s1 is returned.
String
concatenation strncat (str1, str2, size_t n); Appends at most n characters of
string s2 to string s1. The value of s1
is returned.
23
Chapter 4
4.4) String Library Functions (cont’d)
Here below list of string manipulation library functions
String
Function Description
operations
Compares string str1 with string str2. The
function returns a value of
• zero, if str1 is equal to str2
strcmp(str1, str2);
• less than zero, if str1 is less than str2
• greater than zero, if str1 greater than
str2
Note: These are some of the library functions and Many More are available
26
Chapter 4
4.4) String Library Functions (cont’d)
Relational Operators and library functions
supported by C++ String objects
functions Descriptions
append() appends a part of a string to another string
Correspondence between
the C-library and the C++ string class/object
28
Chapter 4
4.4) String Library Functions (cont’d)
Character handling library functions of ctype.h
Prototype Description
isdigit(c ) Returns true if c is a digit and false otherwise
isalpha( c ) Returns true if c is a letter and false otherwise
isalnum( c ) Returns true if c is a digit/letter and false otherwise
isxdigit( c ) Returns true if c is a hexadecimal digit and false otherwise
islower( c) Returns true if c is a lowercase letter and false otherwise
isupper( c) Returns true if c is an uppercase letter; false otherwise
tolower( c ), If c is an uppercase letter, it returns c as a lowercase letter. Otherwise,
toupper( c ) leave the character/string unchanged and vice versa
isgraph( c ) Returns true if c is a printing character other than space (' ')
Returns true if c is a white-space, newline ('n'), space (' '), form feed ('f'),
isspace(c ) carriage return ('r'), horizontal tab ('t'), or vertical tab ('v') and false
otherwise
iscntrl( c ) Returns true if c is a control character and false otherwise
Returns true if c is a printing character other than a space, a digit, or a
ispunct( c )
letter and false otherwise
isprint( c ) Returns true value if c is a printing character including space (' ')
29
Chapter 4
4.4) String manipulation (cont’d)
Example 1: string length
30
Chapter 4
4.4) String manipulation (cont’d)
Example 2: copying and compare (Hard coding )
Reverse string
33
Chapter 4
4.4) String manipulation (cont’d)
Example 5: string tokenization
34
Chapter 4
4.4) String manipulation (cont’d)
Example 6: Program to display the words which start with a capital ‘A’
35
Chapter 4
Practical Exercises 2 - Strings
1. Write a program to count total number of vowels and consonants
present in a string.
2. Design a program to find the frequency of characters within string and
display character with largest and smallest frequency respectively.
3. Write a program that find the frequency of vowel, consonant, digit and
special character
4. Design a program to check either the word is palindrome or not using
loop.
5. Write a program to remove non-alphabet character from string
6. Write a program to store and print the names of your two favorite
television programs. Store these programs in two character arrays.
Initialize one of the strings (assign it the first program’s name) at the
time you declare the array. Initialize the second value in the body of
the program with the strcpy() function.
7. Write an application that inputs a line of text and outputs the text
twice, once in all uppercase and once in all lowercase letters. 36
Chapter 2
Reading Resources/Materials
Chapter 13:
Diane Zak; An Introduction to Programming with C++ (8th Edition),
2016 Cengage Learning
Chapter 8:
Walter Savitch; Problem Solving With C++ [10th edition,
University of California, San Diego, 2018
Link:
https://www.w3schools.in/category/cplusplus-tutorial/
37
Thank You
For Your Attention!!
38