Chapter 5 - Array, Pointers and String

Download as pdf or txt
Download as pdf or txt
You are on page 1of 89

Chapter Five: Array, Pointers and String

Manipulations

COMPUTER PROGRAMMING
Section 1: Array in C++
Array in C++

 The variables we’ve used so far can store a single value. In this
section, we’ll discuss a new type of variable capable of storing a
number of values.

This type is called array.

 Essentially, an array is a data structure that groups elements of the


same type in contiguous memory.

 Problem:

Given 500 numbers, read them in and calculate their average

THEN print out the average


Data Structure Needed

 Need some way to hold all the individual data items after processing
them

 Making individual identifiers a, b, c,... is not practical or flexible

The answer is to use an ARRAY

 A data structure - bigger than an individual variable or constant.

 Data structures containing related data items of same type

 Always remain the same size once created


Properties of an array

 Homogeneous
 Contiguous (Adjacent)
 Have random access to any element
 Ordered (numbered from 0 to n-1)
 Number of elements does not change - MUST be a constant when
declared
int x[6];
1. One Dimensional Here,

2. Multi Dimensional int - type of element to be stored


x - name of the array
6 - size of the array
Declaring Arrays

data_type array_name[number_of_elements];
The number_of_elements, or else the length/size of
the array, is specified by a positive integer constant
When declaring an array, the compiler allocates a
expression enclosed in brackets. All the elements are
memory block to store the values of its elements.
of the same type; it may be of any type (e.g., int,
float, char, …).
These values are stored one after another in
consecutive memory locations.
For example, the statement: int arr[1000]; declares
the array arr with 1000 elements of type int.
Typically, this memory block is allocated in a region
called stack and it is automatically released when the
To realize the importance of arrays, imagine that if
function that declares the array terminates.
C++ did not support this type of aggregate variable,
we’d have to declare 1000 different integer
variables.
Declaring Arrays
 Multiple arrays of the same type can be declared in a single
declaration
 Use a comma-separated list of names and sizes

int c[ 2], d[5 ];

The C++ standard does not allow the size to be specified at runtime. As
said, it must be a constant expression known at compile time. However,
there are C++ compilers that allow the programmer to use a variable for
the declaration. Thus, don’t be surprised if the compiler you are using
compiles the left-side code with dynamic array size.
Exercises

 Write an array declaration for the following


A) A list of 100 floating_point voltage
B) A list of 100 integer years
B) A list of 30 characters
C) A list of 32 floating-point velocities
Declaring Arrays

For example, with the statement


int arr[3];
the compiler allocates 12 bytes to store the values
of the 3 elements.

 If we assume that the memory address of the first element is at position 100,
the value of the first element is stored in positions 100-103, the value of the
second element in positions 104-107, and the value of the third one in
positions 108-111.

 To find the size of the allocated memory, we can use the sizeof operator. For
example, the value of sizeof(arr) is 12.
Fig.7.1 | Array of 12 elements

c is the array name


c has 12 elements ( c[0], c[1], … c[11] )  The value
of c[0] is –45
Accessing Elements

 To access an element, we write the array’s name followed by the element’s


index inside brackets [].

 The index specifies the position of the element within the array, and it must
be an integer constant, variable, or expression.

 In an array of n elements, the first one is stored in position [0], the second
one in position [1], and the last one in [n-1].
Array

 Index
Position number used to refer to a specific location/element
Also called subscript
Place in square brackets [ ]
 Must be positive integer or integer expression
First element has index zero, last element has index n-1

Suppose a class has 27 students, and we need to store the


grades of all of them. Instead of creating 27 separate
variables, we can simply create an array:
double grade[27];
Array Index

 It is important to note the difference between the “seventh element of the


array” and “array element 7.”
 Array subscripts begin at 0, so the “seventh element of the array” has a
subscript of 6, while “array element 7” has a subscript of 7 and is actually the
eighth element of the array.
 Unfortunately, this distinction frequently is a source of off-by-one errors.
 To avoid such errors, we refer to specific array elements explicitly by their
array name and subscript number (e.g., c[ 6 ] or c[ 7 ]).

A popular error of novice programmers is to forget that index numbering starts from
zero. Remember, in an array of n elements, the first element is stored in position zero,
not one, and the last one in position n-1, not n.
Example: Program that accepts 5
integers from user
#include <iostream>
int main()
{
int i, arr[5];
for(i = 0; i < 5; i++)
{
std::cout << "Enter number: ";
std::cin >> arr[i];
}
for(i = 4; i >= 0; i--)
std::cout << arr[i] << '\n';
return 0;
}
Example 2: Accept list of marks and prints
all marks greater than average mark
#include<iostream> average = total / 5;
using namespace std; int ct = 0;
Int main() while (ct < 5)
{ {
int counter = 0,total = 0; if (n[ct] > average)
Int n[5]; cout << n[ct];
float average; ct = ct + 1;
while (counter < 5) }
{ }
cout << "enter a number ";
cin >> n[counter];
total = total + n[counter];
counter = counter + 1;
}
Initializing Array

 Like ordinary variables, an array can be initialized when it is declared.


 Initializing an array in a declaration with an initializer list
 Initializer list
 Items enclosed in braces { }
 Items in list separated by commas
 Example
int n[5] = { 10, 20, 30, 40, 50 };

int n[ ] = { 10, 20, 30, 40, 50 };


Because array size is omitted in the declaration, the compiler determines
the size of the array based on the size of the initializer list
 Creates a five-element array
 Index values are 0, 1, 2, 3, 4
 Initialized to values 10, 20, 30, 40, 50, respectively
Initializing Array

 If the initialization list is shorter than the number of the elements,


the remaining elements are set to the default value of the
element’s type.
 Example
int n[ 10 ] = { 3 };
 Explicitly initializes first element to three
 Implicitly initializes remaining nine elements to zero

If more initializers than elements in the array  Compilation Error


int a[2] = {10, 20, 30}; // Wrong

 We can also use empty {} to initialize all elements with 0.


int a[4] {}; // All elements are set to 0.
Initializing Array

 // declare and initialize and array


 int x[6] = {19, 10, 8, 17, 9, 15};
Examples for - Initialization of arrays

 int a[] = {1, 2, 9, 10}; // has 4 elements


 int a[5] = {2, 5, 4, 1, -2, 5}; // error!
 int a[5] = {2, 3}; // rest are zero
 int a[5] = {0}; // all are zero

can use it with char, float, even bool


Since C++11 it is not necessary to add the =.
int a[] {10, 20, 30, 40};
Constant Array

 If we want the values of an array, whether it is one-dimensional or


multidimensional, to remain the same during program execution, we
declare the array as const.
 A const array must be initialized when it is declared.

const int a[] = {10, 20, 30, 40};

 the a array is declared as const. If we attempt to change the value of any


element the compiler will produce an error message. For example, it is illegal
to write a[1] = 5;
Index out of Range

 Subscripts range from 0 to n-1


 the compiler will NOT tell you if an index goes out of that range - it
cannot detect
 Can make very bad bugs
 From just garbage values in your data to crashing your computer
even damaging your hard drive!
Passing Array to Function
int main()
#include<iostream> {
using namespace std; int v[10];
int c=0;
void display_squared_elements(int a[10])
while(c<10)
{ {
cout<<"Inside called funcition\n"; cout<<"Enter array element";
cin>>v[c];
for(int k=1; k<=10; k++) c++;
{ }
a[k-1]= a[k-1]*a[k-1];
display_squared_elements(v);
cout<<a[k-1]<<endl; cout<<"After function calling\n";
} for(int j= 0; j<10; j++)
{
}
cout<<v[j]<<"\t";
}
}
Exercises

1. Display Sum and Average of Array Elements Using for Loop


2. Write a C++ program that accepts n integer values from user and display
the maximum values from user given list.
Two-Dimensional Array 24

 The form of a two-dimensional array resembles that of a matrix in


math; it is an array of elements of the same type arranged in rows
and columns.
 A two-dimensional array is also called a matrix. It can be of any type
like integer, character, float, etc. depending on the initialization. In
the next section, we are going to discuss how we can initialize 2D
arrays.
 Declaration
 To declare a two-dimensional array, we must specify its name, its
data type, and the number of its rows and columns, like this:

data_type array_name[number_of_rows] [number_of_columns]


Accessing Elements

int a[3][4];

Although a two-dimensional array is visualized as an array with rows


and columns, its elements are stored in consecutive memory locations
in row-major order, with the elements of row 0 first, followed by the
elements of row 1, and so on.
For example, the array a consists of 12 integers stored successively in
memory, which we access as if they were three arrays of four integers.
Accessing Elements

In C++, we can create an array of an array, known as a


multidimensional array.
Initialization

int arr[3][3] =
{
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
 Alternatively, we can omit the inner braces and write:
int arr[3][3] = {10, 20, 30, 40, 50, 60, 70, 80, 90};

Once the compiler fills one row, it continues with the next one. However, the
preferred way is always to use the inner braces so that the initialization of each
row is clearly shown.
Legal initializations or not?
Answer: ________________
int arr[3][3] =
{ int arr[3][3] = {{10, 20, 30}};
{10, 20},
{40, 50},
{70}
};
Example

#include<iostream> int i,j;


using namespace std;
cout<<"Printing a 2D Array:\n";
main( ) for(i=0;i<4;i++)
{ {
for(j=0;j<2;j++)
int arr[4][2] = { {
cout<<"\t"<<arr[i][j];
{ 10, 11 },
}
{ 20, 21 }, cout<<endl;
}
{ 30, 31 }, }
{ 40, 41 }
In the above code,
};
We firstly initialize a 2D array, arr[4][2] with certain values,
After that, we try to print the respective array using two for loops,

the outer for loop iterates over the rows, while the inner one iterates over the columns of the 2D array,
So, for each iteration of the outer loop, i increases and takes us to the next 1D array. Also, the inner loop
traverses over the whole 1D array at a time,
And accordingly, we print the individual element arr[ i ][ j ].
Create and add two matrices

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
m3[i][j]=m1[i][j]+m2[i][j];
}
}
Declaring Multidimensional Arrays 31

const NUM_DEPTS = 5; // mens, womens, childrens, electronics, furniture


const NUM_MONTHS = 12;
const NUM_STORES = 3; // White Marsh, Owings Mills, Towson

int monthlySales [NUM_DEPTS] [NUM_MONTHS] [NUM_STORES];


rows columns sheets
Maximum Size of Declaration

 The maximum memory size that can be allocated for an array


depends on the available memory in the stack.
#include <iostream>
int main()
{
double arr[300000];
return 0;
}

 may not run in your computer, unless the available stack size is large
enough to hold the values.

 When memory is scarce, don’t declare an array with more length


than needed, in order to avoid waste of memory.
Section 2: Pointers
Pointer

 A pointer is a variable that holds the address of something else.


 It is the mechanism to access memory addresses and manipulate
memory directly, and thus, bring you closer to the hardware, which is
essential in order to have a more complete understanding of how
things work.

 Syntax :
dataType *identifier; //To declare a variable
In the general case, if the type is T, the type of T* is “pointer to T”.

As shown, the * character must precede the name of the pointer


variable.
int *x; // x is a pointer to an integer.
Pointer

 In modern computers, the main memory consists of


millions of consecutively numbered memory cells
where each cell stores eight bits of information and
is identified by a unique number, called memory
address.

 For example, in a computer with N bytes of memory,


the memory address of each cell is a unique
number from 0 to N-1, as shown here:
Pointers to anything
x some int
int *x;

z some double
double *z;

y some *int some int


int **y;

Pointer variables can be declared together with other variables of the


same type. For example: int *p, i, j, k;
Assign Value to Pointer Variable

 Toassign a value to the pointer


variable use the address of
operator & X

int x;//variable x
int *p;//pointer p

p
x = 123;
p = &x;
Address of Operator (&)

In C++ you can get the address of a MEMORY


Address
variable with the “&” operator.
0
int x; 1
x = 123; 2
p = &x; x 3 123
4
 &x means “the address of x” 5
 Must always refer to something

...

...
 Must be initialized, cannot be changed
Dereferencing operator(*)

To assign a value to the variable x through the pointer variable

we must use the dereferencing operator *


*p=10; //Changes the value of x from 123 to 10
Equivalent to
x=10;
 You can use the integer x points to in a C++ expression like this:
int x =9; int y; int *p;
p=&x;
y = *p + 17;
*p = *p +1;
cout<<x;
Alternative way of dereferencing
using [index]
#include <iostream>
#include <iostream>
int main() int main()
{ {
int i = 5, *p = &i; int i = 5, *p = &i;
*p = 1; // i=1
p[0] = 1; std::cout << i+*p<< '\n'; // i+i
std::cout << i+p[0] << '\n'; return 0;
return 0; }
}
#include <iostream.h>
int main()
{
int *ptr_a, *ptr_b;
int num_c = 4, num_d = 7;
ptr_a = &num_c;
ptr_b = ptr_a;
cout << *ptr_a << " " << *ptr_b << "\n";
ptr_b = &num_d;
cout << *ptr_a << " " << *ptr_b << "\n";
*ptr_a = *ptr_b;
cout << *ptr_a << " " << *ptr_b << "\n";
The output of this program is:
cout << num_c << " " << *&num_c << "\n"; 4 4
4 7
return 0; 7 7
} 7 7
Assigning a value to a
dereferenced pointer

A pointer must have a value before you can dereference it (follow the
pointer).
int *p; int x;
*p=3; int *p =&x;

*p=3;

this is fine
p points to x
Location and Value Comparisons

 Pointers may be compared for equality


 Same as comparing addresses of what pointers point to
(memory locations:)
 Contents of what pointers point to may be compared, too
 First implies second, not other way around
int *p
//address
5 0xefffdad0 &*p == &*q
p == q
int i int *q
5 0xefffdbd0
*p == *q//content
int j
Pointers and Arrays
In C++, Pointers are variables that hold addresses of other
variables. Not only can a pointer store the address of a single
variable, it can also store the address of cells of an array.
 The name of an array is a pointer to the 0th element of the array (the
beginning of the array)

Syntax: *(arrayname+i) = arrayname[i]

int array[5] ; // array is equivalent to & array[0]


int *ptr;
*array = 5; is like array[0] = 5; int arr[5];
int j = *(array+4) is like int j = array[4] ptr = arr;

cout << *array; is like cout << array[0]; ptr + 1 is equivalent to &arr[1];
ptr + 2 is equivalent to &arr[2];
ptr + 3 is equivalent to &arr[3];
ptr + 4 is equivalent to &arr[4];
…Pointers and Arrays
The close relationship between pointers and arrays is
based on the fact that the name of an array can be
used as a pointer to its first element.

 An array name is basically a const pointer.


 You can use the [] operator with a pointer:

int *p;
int a[10];
p = &a[2]; //p is “the address of a[2] ”
for (int i=0; i<3; i++)
p[i]++; //p[i] is the same as a[i+2]
Exercise: What will be the output
for the following program
#include <iostream>
int main()
{
int i, *ptr1, *ptr2, arr[] = {10, 20, 30, 40, 50, 60, 70};

When two pointers that point to the same array are


ptr1 = &arr[2]; subtracted, the result is the number of elements
ptr2 = &arr[4]; between them, not their distance in memory.
for(i = ptr2-ptr1; i < 5; i+=2) Therefore, although the address of arr[4] is eight
std::cout << ptr1[i] << ' '; places higher than the address of arr[2], the result of
ptr2-ptr1 is equal to the difference of their subscripts,
return 0;
that is, 4-2 = 2.
}
…Pointers

&p, p, and *p all have different meanings

 &p means the address of p

p means the content of p

 *pmeans the content pointed to by p, that is pointed to by


the content of memory location
Exercise: What will be the output
for the following program
#include <iostream>
int main() Since ptr1 points to the address of i the expression:
*ptr1 = i ? 3 : 4; is equivalent to i = i ? 3 : 4;.
{
int *ptr1, *ptr2, *ptr3, i = 0, j = 1, k = 2; Since i is 0, it becomes 4. Since ptr2 points to the
ptr1 = &i; address of j, *ptr2 is equal to j, that is, 1. Therefore, j =
*ptr2 + *ptr1 = 1+4 = 5.
i = *ptr1 ? 3 : 4;
ptr2 = &j; Similarly, since ptr3 points to the address of k, *ptr3 is
j = *ptr2 + *ptr1; equal to k, that is, 2. Therefore, k = *ptr3 + *ptr2 = 2+5 =
7.
ptr3 = &k;
Since the values of *ptr1, *ptr2, and *ptr3 are equal to i,
k = *ptr3 + *ptr2; j, and k, respectively, the program displays: 4 5 7
C.
std::cout << *ptr1 << ' ' << *ptr2 << ' ' << *ptr3 << '\n';
return 0;
}
Pointer Arithmetic

 Canadd an integer quantity to or subtract an integer


quantity from a pointer
 The outcome depends on the size of the object pointed
to
 not the same as integer arithmetic
Pointer Arithmetic

 Integer math operations can be used with pointers.


 If you increment a pointer, it will be increased by the size of whatever
it points to.
int *ptr = a;
*(ptr+2)
*(ptr+4)
*ptr

a[0] a[1] a[2] a[3] a[4]

int a[5];
Section 3: Character and String
Manipulation
STRINGS
CTYPE Built in Functions for Characters
Character Macro Description

isalpha Returns true (a nonzero number) if the argument is a letter of the alphabet.
Returns 0 if the argument is not a letter.
isalnum Returns true (a nonzero number) if the argument is a letter of the alphabet or a
digit. Otherwise it returns 0.
isdigit Returns true (a nonzero number) if the argument is a digit 0–9. Otherwise it
returns 0.
islower Returns true (a nonzero number) if the argument is a lowercase letter.
Otherwise, it returns 0.
isprint Returns true (a nonzero number) if the argument is a printable character
(including a space). Returns 0 otherwise.
ispunct Returns true (a nonzero number) if the argument is a printable character other
than a digit, letter, or space. Returns 0 otherwise.
isupper Returns true (a nonzero number) if the argument is an uppercase letter.
Otherwise, it returns 0.
isspace Returns true (a nonzero number) if the argument is a whitespace character.
Whitespace characters are any of the following:
Example

if (isalpha(input))
#include <iostream>
cout << "That's an alphabetic character.\n";
int main() if (isdigit(input))
cout << "That's a numeric digit.\n";
{
if (islower(input))
char input; cout << "The letter you entered is
lowercase.\n";
cout << "Enter any character: "; if (isupper(input))
cout << "The letter you entered is
cin>>input; uppercase.\n";
if (isspace(input))
cout << "The character you entered
cout << "That's a whitespace character.\n";
is: " << input << endl;
return 0;
cout << "Its ASCII code is: " << }

int(input) << endl;


Program Output with Example
Input
Enter any character: A [Enter]
The character you entered is: A
Its ASCII code is: 65
That's an alphabetic character.
The letter you entered is uppercase.

Enter any character: 7 [Enter]


The character you entered is: 7
Its ASCII code is: 55
That's a numeric digit.
String

 A string literal is a sequence of characters enclosed in double quotes. A


string literal is a constant. In particular, C++ treats it as a nameless constant
character array.

 In particular, when the compiler encounters a string literal, it allocates


memory to store its characters plus the null character to mark its end.

For example, if the compiler encounters the string literal "text", it allocates five
bytes to store the four characters of the string plus one for the null character. A
string literal may be empty. For example, the string literal "" is stored as a single
null character.
String

 C++ provides following two types of string representations:


1. The C-style character string.
2. The string class type introduced with Standard C++.

 Strings are implemented as null terminated arrays of characters.

 char abc[3] = “me” //array abc consists of “m”, “e”, null

 abc = “me” (shortcut for defining and initializing a string)


Types of Strings 58

1. String Literals:
“Hello World”
“xyz 123 *&^#$!”

2. C-Style strings:
char s[20];

3. C++ Class string:


string s;
A common error is to confuse the '\0' and '0'
characters.

C-Style Strings 59
The first is the null character with ASCII code 0,
while the second is the zero character with
ASCII code 48.

 A C-style string is stored in an array of char; To store a C-style string in a variable, we use
 C-style strings should always end in ‘\0’; an array of characters.

Because a C-style string ends with the null


const int MAX_LENGTH(20); character, to store a string of N characters
the size of the array should be N+1 at least.
char s[MAX_LENGTH] =
{ 'H', 'e', 'l', 'l', 'o', ' ', For example, to store a string of up to 4
'W', 'o', 'r', 'l', 'd', '\0'}; characters, we write:
char str[5];

cout << "String = " << s << endl; An array can be initialized with a string,
when it is declared. For example, with the
declaration:
char str[5] = "text";
Internal Storage of C++ Strings

A C++ string is a sequence of characters stored in consecutive memory


locations, terminated by a null character.

e.g. char string[7] = “Bailey”;

char name[20]{ "Alex" }; // only use 5 characters (4 letters + null terminator)

std::cout << "My name is: " << name << '\n';
A flexible way to initialize the array is to omit its length and
let the compiler compute it.

C-Style Strings For example, with the declaration:


char str[] = "text";

Compiler calculates the length of "text" and


then allocates five bytes for str to store the
four characters plus the null character.

 As with an ordinary array, if the number of the characters is less than the size of the
array, the remaining elements are initialized to 0. If it is greater, the compilation fails.

 For example, with the declaration: (Note: ASCII value of '\0' is 0)

char str[5] = "te";

str[0] becomes 't',

str[1] becomes 'e' and the rest elements are initialized to 0, or equivalently to '\0'.

Similarly, with the declaration: char str[5] = {0};

All str elements are initialized to '\0'. When declaring an array of characters to store a C-style
string, don’t forget to reserve an extra place for the null
character.
Exercise

1. Write a program that creates a string #include <iostream>


int main()
with all lowercase and uppercase {
letters of the English alphabet. char str[53];
int i;

for(i = 0; i < 26; i++)


{
str[i] = 'a'+i;
Comments: In each iteration, the ASCII str[26+i] = 'A'+i;
value of the respective character is }
stored in str. For example, in the first str[52] = '\0'; // At the end, we add the null character.
iteration (i=0) we have str[0] = 'a'+0 = 'a' = std::cout << str << '\n';
97 and str[26] = 'A'+0 = 'A' = 65. return 0;
}
Exercise 2: What will be the output
of the following program
Answer: Did you answer Right? Sorry, it is wrong.
#include <iostream>
The '0' does not represent the null character '\0', but it
int main() consists of the ' character, the zero character, and
another '. Therefore, the program outputs
{
Right'0'Wrong. What would be the output if we had
char str[] = "Right'0'Wrong"; written:
std::cout << str << '\n';
char str[] = "Right'\0'Wrong";
return 0;
Since after the first ' the escape sequence \0
}
represents the null character, this time you are right if
you answered Right'.
Exercise 3: C-Style String and
Pointer
#include <iostream> Answer: Since the names of the two arrays are used
using std::cout; as pointers, the expression str1 == str2 checks if the
pointers point to the same address, not if the arrays
int main() are the same. Do str1 and str2 point to the memory
{ same address?
char str1[] = "test", str2[] = "test";
Of course not; str1 and str2 have the same content;
(str1 == str2) ? cout << "One\n" : they are stored in different memory though.
cout << "Two\n"; Therefore, the program displays Two.
return 0;
What would be the output if we write:
} (*str1 == *str2) ? cout << "One\n" : cout << "Two\n";
Since str1 can be used as a pointer to its first element,
*str1 is equal to 't'. Similarly, *str2 is equal to 't'.
Therefore, the program would display One.
C++ Class string 65

 C++ class string requires:


#include <string>
using namespace std;

 To create a variable of type string, simply:


string lastName;

 Assignment, as always it is the same:


lastName = “Marx”;

 Or combine the two with an initialization:


string lastName(“Marx”);

Or
string lastname = “Marx”;
String Operators: Assignment 66

 Assignment (=): As with before, assign a string to a


variable of type string.

string lastName(“Abebe”), anothername;

anothername = lastName;

Both now hold “Abebe”


String Operators: Concatenation 67

 Concatenation (+): Puts a string on the end of another.

string firstName(“Abebe”);
string lastName(“Kebede”);
string fullname = firstName + lastname;
Library Functions Working with
Strings
 The C++ library has numerous functions for handling C-strings .
 These functions perform various tests and manipulations.

 string functions are in <cstring> or <string.h>

 So we need to include the string header file to use the Functions


Function #include<string.h> Description char b[ ] = "Abebe";
strlen Accepts a C-string or a pointer to a string as an argument. Returns the length of the
string (not including the null terminator. Example Usage: len = strlen(name);
strcat Accepts two C-strings or pointers to two strings as arguments. The function appends the
contents of the second string to the first string. (The first string is altered, the second strcpy(dest, source);
string is left unchanged.) Example Usage: strcat(string1, string2);
strcpy Accepts two C-strings or pointers to two strings as arguments. The function copies the
second string to the first string. The second string is left unchanged.
Example Usage: strcpy(string1, string2);
strncpy Accepts two C-strings or pointers to two strings and an integer argument. The third
argument, an integer, indicates how many characters to copy from the second string to
the first string. If the string2 has fewer than n characters, string1 is padded with '\0'
characters. Example Usage: strncpy(string1, string2, n);
strcmp Accepts two C-strings or pointers to two string arguments. If string1 and string2are the
same, this function returns 0. If string2 is alphabetically greater than string1, it returns
a negative number. If string2 is alphabetically less than string1, it returns a positive
number. Example Usage: if (strcmp(string1, string2))
strstr Accepts two C-strings or pointers to two C-strings as arguments, searches for the first
occurrence of string2 in string1. If an occurrence of string2 is found, the function
returns a pointer to it. Otherwise, it returns a NULL pointer (address 0). Example Usage:
cout << strstr(string1, string2);
char name[20]{ "Alex" }; // only use 5 characters (4 letters + null terminator)
cout << "My name is: " << name << '\n';
Examples cout << name << " has " << strlen(name) << " letters.\n";

char a[ ] ="Programing is Fun"; char a[ ] ="Programing is Fun";


char b[ ]="Code"; char b[ ]=“Code";

strcpy(a,b); strncpy(a,b,3);
cout<<a; // Code cout<<a; //Codgraming is fun

char b[6]="Code"; char b[6]="Code";

int size = strlen(b); strcat(b,” is for solution.”);


cout<<size; // 4 cout<<b; // Code is for solution

char b[6]="Code"; char a[ ] ="Programing is Fun";


char c[6]="code"; char b[ ]=“gram";
int res= strcmp(b, c);
cout<<res; //-1 cout<< strstr(a, b); //graming is fun

USING #include<cstring>
converts string to
strlwr()
lowercase

converts string to
strupr()
uppercase
#include <iostream>
#include <cstring>
using namespace std;
strcpy() copies the string pointed to by src into
int main() {
the memory pointed to by dest. Once the null
char str1[] = "String test"; character is copied, strcpy() terminates and
char str2[] = "Hello"; returns the dest pointer.
char one[10];
Since src is declared as const, strcpy() cannot
strncpy(one, str1, 9); modify the string.
one[9] = '\0';
If the source and destination strings overlap the
behaviour of strcpy() and strncpy() is undefined.
cout<< one <<endl;
strncpy(one, str2, 2);
cout << one << endl;
strcpy(one, str2);
cout << one << endl;
}
char source[ ]{ "Copy this!" };

String Copy char dest[5]; // note that the length of dest is only 5 chars!
strcpy(dest, source);

cout << dest << '\n'; // Copy this!

 Because strcpy() does not check if the string pointed to by src fits into the memory
pointed to by dest, it is the programmer’s responsibility to ensure that the destination
memory is large enough to hold all characters.

 Otherwise, the memory past the end of the dest will be overwritten causing the
unpredictable behaviour of the program.

 Since strncpy() specifies the maximum number of the copied characters it is safer than
strcpy().
String Compare
#include <iostream>
#include <cstring>
using namespace std;
int main() {
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") << endl;
cout << strcmp("abc", "ABC") << endl;
return 0;
}
Exercise
if(k == 0)
cout << "Same texts\n";
else
{
int main() cout << "Different texts\n";
{
if(strncmp(str1, str2, 3) == 0)
char str1[100], str2[100];
int k; cout << "But the first 3 chars are the same\n";
cout << "Enter first text: ";
cin.getline(str1, sizeof(str1)); }
return 0;
cout << "Enter second text: ";
}
cin.getline(str2, sizeof(str2));
k = strcmp(str1, str2);
/* We could omit the declaration of k and write: if(strcmp(str1, str2) == 0) */
CTYPE String or String Class?

 Unless you have a specific, compelling reason to use C-style strings,


use std::string (defined in the <string> header).

 std::string is easier, safer, and more flexible.

 In rare case that you do need to work with fixed buffer sizes C-style
strings (e.g. for memory-limited devices) would be recommended
than well-tested 3rd party string library.
Comparison

Feature CTYPE strings String classes

Data type Array of characters Object

Memory management Manual Automatic

Flexibility Less flexible More flexible

Complexity Simpler to use More complex to use

Simple string manipulation More complex string


Best use cases
tasks manipulation tasks
For greater flexibility, convenience, and safety
in handling strings, C++ provides the string
class.
string s3;
string s(“Hi”);
s3=s1+s2;
s1.append(s2);
(s1==s2)
(s1<s2)
s1.length();
s1.find(‘a’);
src.copy(des, len);
#include <iostream>
EXAMPLE FOR STRING CLASS
#include <string>
using namespace std;
// Compare two strings
int main() {
if (str == "Hello, world!") { // CTYPE: strcmp(str1, str2)
string str = "Hello, World!"; cout << "The strings are equal" << endl;
}
// Append Hello Ethiopia and print string content
else
cout << str.append(", Hello Ethiopia.")<< endl; {
// CTYPE strcat(str1, str2); cout << "The strings are not equal" << endl;
}
// Append a new character to the end of the string
str += '!'; // Find the first occurrence of a character in a string
int index = str.find("l");
// If the character is found, print its index
//Check length if (index != string::npos) {
cout << "The character 'l' is found at index " << index << endl;
int len = str.length(); // str.size(); --- CTYPE: strlen(str) }
cout<<endl<<len<<endl;
//str1.copy(str2,len,pos); source.copy(desination, legth, position);
// destination - fixed array
// Change the first character of the string char str3[50]; // CTYPE: strncpy(str1, str2);
str.copy(str3, 20);
str[1] = 'a'; cout<<str3;
// str[1] = "a"; str[1] = "aa"; str[1] = "h\0"
return 0;
// Print the string again }
cout << str << endl;
#include <iostream>
EXAMPLE FOR STRING CLASS
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
cout << str.append(", Hello Ethiopia.")<< endl; char str3[50]; // CTYPE: strncpy(str1, str2);
str += '!'; str.copy(str3, 20);
int len = str.length(); cout<<str3;
cout<<endl<<len<<endl;
return 0;
str[1] = 'a';
}
cout << str << endl;
if (str == "Hello, world!")
{ cout << "The strings are equal" << endl; }
else { cout << "The strings are not equal" << endl; }
int index = str.find(“z");
cout<<index;

if (index != -1) {
cout << "The character 'l' is found at index " << index <<
endl; }
String Input

 When the input stream cin is used space characters, newline , tab,
etc. are used as separators and terminators.
 skips over any leading spaces
 terminates reading a value when it finds a white-space character

char name[20];
cout<<“enter your name”;
cin>>name;
cout << "Enter your name: ";
Input: My name is Abebe cin.get(p1.name, 50); // for CTYPE
Output: My
getline(cin, str); // for string class
Example

#include<iostream>
using namespace std;
int main()
{
string fullname;
cout<<"Enter your full name";
//cin>>fullname; // Accepts input until the first space
//cin.get(fullname, 30); // works for 30 characters input (CTYPE)
getline(cin, fullname); // string class based approach

cout<<"Hi, "<<fullname;

}
String Input …

#include <iostream>
using namespace std;
int main()
{
char line[80];
int count = 0;

cout << "Enter a sentence of no more than 79


characters:\n";
cin.getline(line, 80);
cout << "The sentence you entered is:\n";
cout << line;
return 0;
}
String Output

 A string is output by sending it to an output stream that is using cout.


 E.g
char str[20]=“hello”;
cout<<“ the string str is:”<<str;

 char str[] = "Print a message";

 cout << str;

 If we want to display a certain number of characters we can use the write()


function, which is a member of the ostream class. For example, if we write:
cout.write(str, 3);
Program Output with Example Input

Enter a sentence of no more than 79


characters:

C++ Programming is fun! [Enter]

The sentence you entered is:


C++ Programming is fun!
Exercises

1. Write a Program that counts and returns the number of vowels in


the string. (For the purposes of this exercise, we are talking about
the standard 5 vowels -- A, E, I, O, U).

2. Write a Program that counts and returns the number of consonants


in the string.

3. Write a Program that converts the string to all lowercase.

4. Write a Program that converts the string to all uppercase.


Homework: Palindrome or not

 Write a program that reads a string and stores it in a string object. Then, the
program should display a message to indicate if it is a palindrome or not,
that is, if it can be read the same in either direction. For example, the string
level is a palindrome, since it is read the same in both directions.

 Comments: The loop compares the characters from the first character up to
the middle one with the characters from the last one back to the middle.
That’s why the loop is executed from 0 up to len/2. The last character is
stored in str[len-1].
End of Chapter 5

You might also like