Chapter 4
Chapter 4
P This code will copy the elements of array y into x, overwriting the original
contents of x.
P A loop like this has to be written whenever an array assignment is needed.
ü An array may have more than one dimension.
ü Each dimension is represented as a subscript in the array.
ü Therefore a two dimensional array has two subscripts, a three dimensional
array has three subscripts, and so on.
ü Arrays can have any number of dimensions, although most of the arrays that
you create will likely be of one or two dimensions.
ü A chess board is a good example of a two-dimensional array. One dimension
represents the eight rows, the other dimension represents the eight columns.
ü Syntax
Type Multi_arrayName [ ] [ ];
P To initialize a multidimensional arrays , you must assign the list of values to
array elements in order, with last array subscript changing while the first
subscript holds steady.
P The program initializes this array by writing
int theArray[5][3] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
P for the sake of clarity, the program could group the initializations with braces,
as shown below.
int theArray[5][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13,
14,15} };
P If a one-dimensional array is initialized, the size can be omitted as it can be
found from the number of initializing elements:
int x[] = { 1, 2, 3, 4} ;
ü This initialization creates an array of four elements.
P Note however:
int x[][] = { {1,2}, {3,4} } ; // error is not allowed.
ü and must be written
int x[2][2] = { {1,2}, {3,4} } ;
PString is nothing but a sequence of character in which the last
character is the null character ‘\0’.
PThe null character indicates the end of the string.
PAny array of character can be converted into string type in C++
by appending this special character at the end of the array
sequence.
PSyntax
char StringName[ ];
PFor example a string variable s1 could be declared as follows:
char s1[10];
PThe string variable s1 could hold strings of length up to nine
characters since space is needed for the final null character.
PStrings can be initialized at the time of declaration just as other
variables are initialized. For example:
char s1[] = "example";
char s2[20] = "another example"
ü would store the two strings as follows:
s1 |e|x|a|m|p|l|e|\0|
s2 |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|
ü Note that the length of a string does not include the terminating
null character.
ü A string is output by sending it to an output stream, for example:
cout << "The string s1 is " << s1 << endl;
ü would print
The string s1 is example
ü When the input stream cin is used space characters, newline etc.
are used as separators and terminators.
ü Thus when inputting numeric data cin skips over any leading
spaces and terminates reading a value when it finds a white-
space character (space, tab, newline etc. ).
ü This same system is used for the input of strings, hence a string
to be input cannot start with leading spaces, also if it has a space
character in the middle then input will be terminated on that
space character.
ü To read a string with several words in it using cin we have to call cin once
for each word.
ü For example to read in a name in the form of a First_name followed by a
Last_name we might use code as follows:
char firstname [12], lastname[12];
cout << "Enter name ";
cin >> firstname ;
cin >> lastname;
cout << "The name entered was "
<< firstname << " "
<< lastname;
ü To read text containing blanks we use another function, cin.get( ).
#include<iostream.h>
void main()
{
const int max=80;
char str[max];
cout<<"\n Enter a string;";
cin.get(str , max); // max avoid buffer overflow
cout<<"\n You entered : "<<str;
}
Reading multiple lines
ü We have solved the problem of reading strings with embedded blanks,
but what about strings with multiple lines?
ü It turns out that the cin.get() function can take a third argument to
help out in this situation.This argument specifies the character that
tells the function to stop reading.
ü The default value of this argument is the newline('\n')character, but if
you call the function with some other character for this argument, the
default will be overridden by the specified character.
ü In this example, we call the function with a dollar sign ('$') as the third
argument
//reads multiple lines, terminates on '$' character
#include<iostream.h>
void main(){
const int max=80;
char str[max];
cout<<"\n Enter a string:\n";
cin.get(str, max, '$'); //terminates with $
cout<<\n You entered:\n"<<str; }
String constants
PYou can initialize a string to a constant value when you define it.
Here's an example'
#include<iostream.h>
void main(){
char str[] = "Welcome to C++ programming language";
cout<<str;
}
Copying string the hard way
ü The best way to understand the true nature of strings is to deal with them
character by character
#include<iostream.h>
#include<string.h> //for strlen()
int main(){
const int max=80;
char str1[]='‘ my Captain! our fearful trip is done";
char str2[max];
for(int i=0; i<strlen(str1);i++)
str2[i]=str1[1];
str2[i]='\0';
cout<<endl;
cout<<str2;
}
Copying string the easy way
ü You can copy strings using strcpy or strncpy function.
ü We assign strings by using the string copy function strcpy.
ü The prototype for this function is in string.h.
strcpy(destination, source);
ü strcpy copies characters from the location specified by source to the location
specified by destination.
ü It stops copying characters after it copies the terminating null character.
ü The return value is the value of the destination parameter.
Copying string the easy way
ü You must make sure that the destination string is large enough to hold all of
the characters in the source string (including the terminating null character).
Example:
#include <iostream.h>
#include <string.h>
void main(){
char me[20] = "David";
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
return;
}
PThere is also another function strncpy, is like strcpy, except
that it copies only a specified number of characters.
strncpy(destination, source, int n);
P It may not copy the terminating null character.
It may not copy the terminating null character.
Example
#include <iostream.h>
#include <string.h>
void main() {
char str1[] = "String test";
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';
cout << one << endl;
strncpy(one, str2, 2);
cout << one << endl;
strcpy(one, str2);
cout << one << endl;
}
Concatenating strings
ü In C++ the + operator cannot normally be used to concatenate
string, as it can in some languages such as BASIC; that is you
can't say: str3 = str1 + str2;
ü You can use strcat() or strncat
ü The function strcat concatenates (appends) one string to the end
of another string.
strcat(destination, source);
ü Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
}
P The function strncat is like strcat except that it copies only a specified
number of characters.
strncat(destination, source, int n);
P It may not copy the terminating null character.
Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strncat(str1, "def", 2);
str1[5] = '\0';
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
}
Comparing strings
ü Strings can be compared using strcmp or strncmp functions
ü The function strcmp compares two strings.
strcmp(str1, str2);
strcmp returns: < 0 if str1 is less than str2
= 0 if str1 is equal to str2
> 0 if str1 is greater than str2
Example:
#include <iostream.h>
#include <string.h>
void 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;
PThe function strncmp is like strcmp except that it compares
only a specified number of characters.
strncmp(str1, str2, int n);
P strncmp does not compare characters after a terminating null
character has been found in one of the strings.
Example:
#include <iostream.h>
#include <string.h>
void main()
{
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
}
Thank you!!!