Fundamentals of Programming - Chapter#6
Fundamentals of Programming - Chapter#6
1
String-Concept
2
String Taxonomy and Representation
String
Variable-length String
Variable size. Can expand or contract to accommodate the
data.
Based on the way the end of data represented, there are two
types:
• Delimited
• Length-controlled
4
Delimited String
Delimited String
• The string is represented as an array of characters delimited
by a special character.
• C++ uses the ASCII null character( ASCII code 0), represented
as escape sequence ‘\0’, as a string delimiter.
• The string can store up to size -1 characters where size is the
size of the array. One byte is left for the delimiter
• The delimited string is also called C-string style.
C-string in memory
G i r m a D a w i t \0
5
Declaration of C++-string
6
Initialization of C++-string
C-string can be initialized in two ways:
• Using the usual array initialization
Syntax:
char str_name[size]={charVal1, charVal2…charVallast, ‘\0’} ;
Example
char studentName[31]={‘G’, ‘i’, ‘r’, ‘m’, ‘a’, ‘ ’, ‘D’, ‘a’, ‘w’, ‘i’, ‘t’ ‘\0’};
• Using string literal
Syntax:
char str_name[size]=string_literal;
Example
char studentName[31]=“Girma Dawit”;
Note: The length of the string at least should be one less from the
size of the array
7
Reading and Writing C++-string
The one place where C++ allows aggregate operations on arrays is the
input and output of C-strings (that is, character arrays)
Reading
Syntax: cin >> strVar;
cin is not capable of receiving multi-word string such as “hello world”.
This is because the cin “>>” operator considers a space to be a
terminating character. Thus it will read strings consisting of single word,
but anything typed after a space is thrown away.
To read strings with blanks, use get:
• cin.get(cstr, m+1);
Stores the next m characters into cstr but the newline character is not
stored in cstr. If the input string has fewer than m characters, the reading
stops at the newline character
• cin.getline(cstr, n, ch); // read to a maximum of n chrs or up to
character ch which ever occur first.
• cin.getline(cstr, n); //read to end-of-line
8
Reading…
Writing
Syntax: cout << str;
outputs the content of str on the screen
• << continues to write the contents of str until it finds the
null character
• If str does not contain the null character, then we will see
strange output. << continues to output data from
memory adjacent to name until '\0' is found. Your
program may crash if it interferes with other programs
memory.
9
Reading…
#include <iostream.h>
int main ()
{
char mystr1[50], mystr2[50];
cout << "What's your name? ";
cin >> mystr1
cout << "Hello " << mystr1 << ".\n"; //if the user enters “Dawit Girma” , output?
cout << "What's your name? ";
cin.getline (mystr2, 49);
cout << "Hello " << mystr2 << ".\n"; //if the user enters “Dawit Girma” , output?
return 0;
}
10
C++ string Manipulation
11
String Copy Function
strcpy() function: used to copy one string to another.
Syntax: strcpy(destination, source);
Example:
strcpy(studentName, “Mesfin Girma” );
Caution: if the destination array being too small to hold the
information, the copy function destroys the content of adjacent
memory causing the program to abort, or running with corrupted
data.
To avoid the above problem use the strncpy() function
Strncpy() function: Copies at most n characters of source to
destination. If destination has fewer than n characters, it pads
with '\0's.
Syntax: strncpy(destination, source, n)
12
String Concatenation Function
strcat() function: appends source to the end of the string value
contained in destination.
Syntax: strcat(destination, source);
Example:
strcat(message, newmessage );
Caution: if the destination array being too small to hold the
information, the copy function destroys the content of adjacent
memory causing the program to abort, or running with corrupted
data.
To avoid the above problem use the strncat() function
Strncat() function: Copies at most n characters of source to
destination. If destination has fewer than n characters, it pads
sdestination with '\0's.
Syntax: strncat(destination, source, n)
13
String Compare Function
strcmp(): Compares stringExp1 with stringExp2. Returns a negative
integer if stringExp1 < stringExp2, 0 if stringExp1==stringExp2, and
a positive integer if stringExp1 > stringExp2. The comparison is
case sensetive.
Syntax: strcmp(stringExp1, stringExp2);
Example
strcmp(studentName, “Mesfin Girma”);
strncmp(): Compares at most n characters of stringExp1 with
stringExp2. Returns the same values as strcmp() based on the
number of characters compared.
Syntax: strncmp(stringExp1, stringExp2, n);
Example
strcmp(studentName, “Mesfin Girma”, 3);//Comparison is based
only on the first three characters.
Strcmpi() is used for case insensitive comparison
14
C++ string Length Function
strlen(): returns the length of the string. Does not include the
'\0' in the length count.
Syntax: strlen(str);
Example:
char studentName[20]=“Abebe Kebede”;
int size=strlen(“Dawit Girma”); //size assigned 11
int size=strlen(studentName);// ?
15
Example
16
Example
17
Length Controlled String
10 G i r m a D a w i t
18
Declaration and Initialization of C++ String
For using C++ class string, the program must include a header file knows as
<string>.
Declaration Syntax:
string strVar;
The declaration for strVar creates a string object of length zero, but the
program automatically resizes str1 when it reads input into strVar:
Example:
string studentName;
Initialization Syntax:
string strVar1=literalString;
string strVar2= strVar1;//strVar1 is prior declared and initialized
Example:
#include <string>
string str1=“Hello You”;
string str2=str1; 19
Reading and Writing with C++ String
you can use cin with the >> operator to read a one
word string object and
cout with the >> operator to display a string object
using the same syntax you use with a C-style string.
But reading a line at a time instead of a word at time
uses a different syntax. No length specifier is
required.
• getline(cin, str1); // read to end-of-line
• getline(cin, str2, ch); // read to character ch
20
Operation with C++ String
Unlike C-string, aggregate operation such as assignment, concatenation,
appending and comparison is allowed with C++ string.
Assuming the following declaration
string str1=“Hello There.”, str2;
Assignment
str2=str1; //valid
Concatenation
str2= str1 + “ It is me.”;
Appending
str1= str1 + “ It is me.”;//equivalent to str1+= “ It is me.”;
Comparison
If(str1 > str2) //using relational operator(<, <=, >, >=, ==, !=) is valid
…;
21
Operation with C++ String
C++ also provides different functions to manipulate string. They all can be
accessed using the dot notation:
strVar.functionName
Assuming the declaration next
string str1=“Hello There. ”, str2=“It is me.”;
String length function
Returns the length of string.
Syntax: strVar.size();
Example: int size=str1.size(); //size is assigned 11.
String compare function
Returns positive integer if strVar1 > strVar2, negative integer if strVar1 <
strVar2, zero otherwise.
Syntax: strVar1.compare(strVar2);
Example: if(str1.compare(str2) >0)
…; 22
Reading and Writing with C++ String
23
Character by Character Manipulation
Both C and C++ string can be manipulated character by character using
index notation.
Example C String
char our_string[5] = "Hi";
int index = 0;
while (our_string[index] != '\0'){
our_string[index] = 'X';
index++;
}
Example C ++ String
string our_string = "Hi";
int index = 0;
while (index <= our_string.size()){
our_string[index] = 'X';
index++;
24
}
Array of C++-string
An array of string is represented with C++ as two dimensional array. It is
declared as
char arrayName[arraySize][stringSize];
For example an array to hold a maximum of 50 student name is declared as
char name[50][16];
name[0] A b e b e K e b e d e /0
name[1] H i r u t D a w i t /0
N e b i H a g o s /0
name[20] M i m i M a m o /0
name[21] B r u k K a s a /0
name[48] T e s f a y e M o g e s /0
name[49] B e t i S o l o m o n /0
25
Array of …
Because each row represent a single C-string , we can read data
in to an array of C-string as follows:
char name[50][16];
//Reading
for(int j=0; j<50; j++)
cin.getline(name[j], n);
//Printing
for(int j=0; j<50; j++)
cout << name[j] << endl;
Note: Look the waste of space when using C-string.
26
Array of C++ String
An array of string is represented with C++ String as one
dimensional array of type string.
It is declared as
string arrayName[size];
Example
string name[50];
//Reading
for(int j=0; j<50; j++)
getline(cin, name[j]);
//Printing
for(int j=0; j<50; j++)
cout << name[j] << endl;
27