06 Arrays and String
06 Arrays and String
2
Defining Arrays
When defining arrays, specify: • Type declares the base type of
1. Array Name . the array that determines the
2. Type of array . data type of each element in the
array .
3. size of the arrays .
• Size defines how many elements
the array will hold. The Size must
The general form : be an integer constant greater
than zero.
Type array_Name [ size ];
3
Defining Arrays - Examples-
int A[10];
An array of ten integers .
Char str[20];
An array of twenty characters .
int a[ 100 ], b[ 27 ] ;
Defining multiple arrays of same type .
4
Defining and Initializing an Array
Define an array temperature of double temperature [5] = {12.3 , 7.5 , 65 , 72.1, 87.5 };
temperature [5]
temperature [2] 65.0 Elements
Initialize it with these numbers:
12.3 , 7.5 , 65 , 72.1, 87.5 temperature [3] 72.1
Index
5
Initializing Arrays
int N[ ] = { 1, 2, 3, 4, 5 };
If size omitted, the size is determined from the 5 initializers .
int N[5] = { 0 } ;
int B[20] = {2, 4, 8, 16, 32};
Unspecified elements are guaranteed to be zero .
If not enough initializers, rightmost elements become 0 .
int C[4] = {2, 4, 8, 16, 32};
Error — compiler detects too many initial values .
C++ arrays have no bounds checking .
int D[5] = {2*n, 4*n, 8*n, 16*n, 32*n};
Automatically only ; array initialized to expressions .
6
Accessing Array Elements
An individual element within array is accessed by use of a subscript
(index) that describes the position of an element in the array , it must
be an integer or integer expression .
Array named c of size n:
c[0],c[1],...,c[ n–1 ]
int A[10];
A[0], A[1], …, A[9]
In C++ , all array have zero as the index of first element .
7
Accessing Array Elements
• Array elements are like normal variables :
temperature [3] = 12.7 ;
cin >> temperature [3] ;
or
N = 3;
temperature [N] = 12.7;
temperature [5-2] == temperature [3] == temperature [N]
8
Assigning Values
• You cannot assign one array to another :
int a[10] , b[10] ;
a=b ; //error … illegal
• Instead, we must assign each value individually .
9
Manipulating Arrays
Reading elements .
Printing elements .
10
Manipulating Arrays
Initializing Array Elements :
• To access all elements of an array a for loop is used. It will start from
index 0 to the last element in the array which has an index of array
size-1.
11
Manipulating Arrays
Reading Elements :
CS 103 13
Strings in C
• In C, a string can be a specially terminated char array or char pointer
• a char array, such as char str[ ]=“high”;
• a char pointer, such as char *p = “high”;
• If a char array, the last element of the array must be equal to ‘\0’, signaling the end
• For example, the above str[] is really of length 5:
str[0]=‘h’ str[1]=‘i’ str[2]=‘g’ str[3]=‘h’ str[4]=‘\0’
• The same array could’ve been declared as:
• char str[5] = {‘h’,’i’, ‘g’,’h’,’\0’};
• If you write char str[4] = {‘h’,’i’, ‘g’,’h’};, then str is an array of chars but not a string.
• In char *p=“high”; the system allocates memory of 5 characters long, stores “high” in
the first 4, and ‘\0’ in the 5th.
CS 103 14
The string Class in C++
• C++ has a <string> library
• Include it in your programs when you wish to use strings: #include
<string>
• In this library, a class string is defined and implemented
• It is very convenient and makes string processing easier than in C
CS 103 15
Declaration of strings
• The following instructions are all equivalent. They declare x to be an
object of type string, and assign the string “high school” to it:
• string x(“high school”);
• string x= “high school”;
• string x; x=“high school”;
CS 103 16
Operations on strings (Concatenation)
• Let x and y be two strings
• To concatenate x and y, write: x+y
string x= “high”;
string y= “school”;
string z;
Output:
z=x+y;
z=highschool
cout<<“z=“<<z<<endl;
z =z+“ was fun”;
z= highschool was fun
cout<<“z=“<<z<<endl;
CS 103 17
Concatenation of Mixed-Style Strings
• In where s is of type string,
• u can be s=u+v+w;
A string object, or
a C-style string (a char array or a char pointer),
a C-style char
or a double-quoted string,
or a single-quoted character.
• Same with v and w.
• At least u or v or w must be a string object
CS 103 18
Example of Mixed-Style Concat
string x= “high”;
char y[]= “school”;
char z[]= {‘w’,’a’,’s’,’\0’};
char *p = “good”;
string s= x+y+’ ‘+z+” very”+” “+p+’!’;
cout<<“s=“<<s<<endl;
cout<<“s=“+s<<endl;
Output:
s=highschool was very good!
s=highschool was very good!
CS 103 19
The concat-assign Operator +=
• Assume x is a string object.
• The statement
x += y;
is equivalent to
x=x+y;
where y can be a string object, a C-style string variable, a char
variable, a double-quoted string, or a single-quoted char.
CS 103 20
Comparison Operators for string Objects
• We can compare two strings x and y using the following operators: ==,
!=, <, <=, >, >=
• The comparison is alphabetical
• The outcome of each comparison is: true or false
• The comparison works as long as at least x or y is a string object. The
other string can be a string object, a C-style string variable, or a
double-quoted string.
CS 103 21
Example of String Comparisons
string x= “high”;
char y[]= “school”;
char *p = “good”;
If (x<y) Output:
cout<<“x<y”<<endl; x<y
If (x<“tree”) x<tree
cout<<“x<tree”<,endl; low != x
If (“low” != x) p>x
cout<<“low != x”<<endl;
if( (p>x)
cout<<“p>x”<<endl;
Else
cout<<“p<=x”<<endl;
CS 103 22
The Index Operator []
• If x is a string object, and you wish to obtain the value of the k-th
character in the string, you write: x[k];
string x= “high”;
char c=x[0]; // c is ‘h’
c=x[1]; // c is ‘i’
c=x[2]; // c is g
23
Getting a string Object Length &
Checking for Emptiness
• To obtain the length of a string object x, call the method length() or
size():
int len=x.length( );
--or--
int len=x.size( );
CS 103 24
Obtaining Substrings of Strings
• Logically, a substring of a string x is a subsequence of consecutive
characters in x
• For example, “rod” is a substring of “product”
• If x is a string object, and we want the substring that begins at position
pos and has len characters (where pos and len are of type int), write:
string y = x.substr(pos,len);
CS 103 26
Replacing a Substring by Another
• Suppose x is a string object, and suppose you want to replace the
characters in the range [pos,pos+len) in x by a string y.
• To do so, write: x.replace(pos,len,y);
CS 103 27
Deleting (Erasing) a Substring of a string
Object
• Suppose x is a string object, and suppose you want to delete/erase
the characters in the range [pos,pos+len) in x.
• To do so, write: x.erase(pos,len);
CS 103 28
Searching for (and Finding) Patterns in
Strings
• Suppose x is a string object, and suppose you want
to search for a string y in x.
• To do so, write: int startLoc = x.find(y);
CS 103 29
Searching for Patterns (Contd.)
• To search for the rightmost occurrence of y in x, do
• In all the versions of find and rfind, the argument y can be a string
object, a C-style string variable, double-quoted string, a char variable,
or a single-quoted char.
startLoc = x.rfind(y); // or
startLoc = x.rfind(y, pos);
CS 103 30