CSC-113
Computer
Programming
Lecture 9 – Strings
OBJECTIVES
• declaring string object
• initializing string object
• reading string input
• string concatenation
• string comparison
• access a character of string
• operation on string object
• some string manipulation functions
• Comparison c-string and c++ string
String
• The string is any sequence of characters
• Every string is terminated by a ‘\0’ character. • To use strings, you need to include the header
<string>
• The string is one of the C++ built-in classes.
• C++ strings allow you to directly initialize, assign,
Declaring string Objects
• Use the class name string and then list object names. • Example:
string str; // declaring one object called str
Initializing string
Objects
• The string objects can be an initialize with the =
operator.
• C++ automatically reserves sufficient memory
string str1 = "This is an example.";
Reading a string input
• To read a single word:
cin >> str1;
• Reads characters until whitespace typed • Whitespace includes space and "Enter" key
• To read a single line of input:
Example
string name;
cout << "Enter your name: " << endl; cin >> name;
cout << “Welcome " << name <<“\n Have a nice day \n”;
Enter your name:
Majed Ali
Example
string name;
cout << "Enter your name: " << endl; getline (cin, name);
cout << “Welcome " << name <<“\n Have a nice day \n”;
Enter your name:
Majed Ali
Strings concatenation
with the + operator
• C++ strings also provide many string manipulation facilities.
The simplest string manipulation that we commonly use is concatenation, or addition of strings. In C++, we can use the + operator to concatenate (or “add”) two strings, as shown below:
string result; string s1 = "hello "; string s2 = "world"; result = s1 + s2; // result now contains "hello world" Notice that
Strings concatenation
with the + operator
• You can also use two or more + operators to
concatenate several (more than 2) strings.
string firstname, lastname, fullname;
cout << "First name: ";
getline (cin, firstname); // if firstname = “Ahmed”
cout << "Last name: ";
getline (cin, lastname); // if lastname = “Ali”
fullname = lastname + ", " + firstname;
// fullname = “Ali, Ahmed”
• We can also use the + to concatenate multiple
strings to be printed as one string.
fullname = lastname + ", " + firstname; cout << "Fullname: " << fullname << endl;
cout << "Fullname: "+lastname+ ", " + firstname <<endl;
cout <<"Fullname:"+lastname+ ", " + firstname + ”\n”;
Comparing string
Objects
• Equality and relational operators perform
comparisons using the numerical values of the characters in each string.
Operator Action
== True if strings identical
!= True if strings not identical
> True if first string greater than second < True if first string is less than second
Example
• string s1 = "abc def abc";
string s2 = "abcde uvwxyz";
• s1< s2 ??
• Uses ASCII code to determine which string is
smaller.
• Here the condition is true because a space comes
Access a character of
string
• The subscript operator, [ int ], can be used with
strings to access and modify individual characters.
• The strings have a first subscript of 0.
string x = “high”;
char c = x[0]; // c is ‘h’
c = x[1]; // c is ‘i’
Operators on string Objects
Type Operator Action
Assignment = Stores string
+= Concatenates and stores
Comparison == True if strings identical != True if strings not identical
> True if first string greater than second < True if first string is less than second
>= True if 1st string greater or equal than
2nd
<= True if 1st string less or equal than
2nd
Input/Output >> For input and string objects << For output and string objects
Character [ ] To access individual characters access
Some string Functions
• More actions needed than operators can be
provided by using string class’s functions - Examples: length, find,…etc
• Calling member function involves using object
String manipulation
Functions
Functions Description
Append() Adds one string at the end of another string
Assign() Assign a specified part of string
At() Access a character located at given location
Begin() Returns a reference at the beginning of the string
Capacity() Calculates the total elements that can be stored
Compare() Compare two strings
Empty() Returns false if the string is not empty , otherwise true.
End() Returns a reference to the termination of the string
Erase() Erases the specified character
Find() Finds the given substring in the source string
String manipulation
Functions
Functions description
Length() Calculates the total number of elements in the string Replace() Substitute the specified character in the given string Resize() Modify the size of the string as specified
length Function
• To obtain the length of a string object, call the
method length()
ob. length()
- it return the length of the ob.
str = "exam";
n = str.length(); //n=4
append Function
• Str1.append(str2);
substr Function
• We can extract one portion of a string with the
method substr.
• This does not remove the portion from the original
substr Function
• The required substring is specified by the starting
position and the number of characters, taking into account that the position of the first character in the string is 0. ob.substr( int, int)
position Number of character
string text = "hello world, this is a test"; string fragment = text.substr(6, 5);
// start at 6, take 5 characters
empty Function
• the empty function determines whether a string object is
empty or not.
ob.empty();
• The function empty returns true if the string is empty;
otherwise, it returns false.
Str = “ Hi “;
bool flag = Str.empty(); // flag = False
insert Function
• Adds characters (string) to a string object
str1.insert(pos1, str2);
• index is beginning position
• ob2 represents what is to be inserted
s1 = "This is an example."; s1.insert (8,"just ");
String str1=“hello world”; String str2=“to this”
Str1.insert(pos1,str2,pos2,len2); Str1.insert(6,str2,0,3);
compare Function
• String s1 = “abd”, s2 = “abc”;
• Int d = s1.compare(s2);
• If(d==0)
• Cout<<“both strings are identical”;
• Else if (d>0)
• Cout<<“s1 is greater then s2”;
• Else
erase function
• String s1 = “abc1234pqr”; • S1.erase(3,5);
size & empty Function
• String s1 = “abc”;
• Cout<<s1.size();
• Cout<<(s1.empty()? “True” : “false”)<<endl;
Acessing Elements of
String: at()
• String s1 = “abcdefghijkl”;
• For(int i=0 ; i< s1.length();i++)
• Cout<<s1.at(i); //using at()
• For(int i=0 ; i< s1.length();i++)
The C-Style Character
String:
• The C-style character string originated within the C
language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
• The following declaration and initialization create a string
consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows:
char greeting[] = "Hello";
• Actually, you do not place the null character at the
end of a string constant. The C++ compiler
#include <iostream> using namespace std; int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; cout << "Greeting message: ";
cout << greeting << endl; return 0;
} When the above code is compiled and executed, it produces result
something as follows:
Following example makes use of
few of the above mentioned
functions:
• #include <iostream>
• #include <cstring>
• using namespace std;
• int main ()
• {
• char str1[10] = "Hello"; char str2[10] = "World"; char str3[10]; int len ;
• // copy str1 into str3
• strcpy( str3, str1);
• cout << "strcpy( str3, str1) : " << str3 << endl;
• // concatenates str1 and str2
• strcat( str1, str2);
• cout << "strcat( str1, str2): " << str1 << endl;
• // total lenghth of str1 after concatenation
• len = strlen(str1);
• cout << "strlen(str1) : " << len << endl;
• return 0;
• Output:
•
Strcpy( str3, str1) : Hello
Comparision between c & c++ String
ACTION C++ String C String
Input << getline << getline
Output >> >>
Copy = Strcpy strncpy
Compare Relational operators to
compare Strcmp strncmp Concatenation + += append Strcat strncat
Extraction Substr strstr
Search for substring Find rfind strstr
Search for character Find rfind Strchr strnchr Access character At [ ] Strchr [ ]
Insert Insert
Erase Erase clear
Swap swap