• No results found

CSC 120 Lecture9(Strings)

N/A
N/A
Protected

Academic year: 2020

Share "CSC 120 Lecture9(Strings)"

Copied!
39
0
0

Loading.... (view fulltext now)

Full text

(1)

CSC-113

Computer

Programming

Lecture 9 – Strings

(2)

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

(3)

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,

(4)

Declaring string Objects

Use the class name string and then list object names.Example:

string str; // declaring one object called str

(5)

Initializing string

Objects

The string objects can be an initialize with the =

operator.

C++ automatically reserves sufficient memory

string str1 = "This is an example.";

(6)

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:

(7)

Example

string name;

cout << "Enter your name: " << endl; cin >> name;

cout << “Welcome " << name <<“\n Have a nice day \n”;

Enter your name:

Majed Ali

(8)

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

(9)

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

(10)

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”

(11)

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”;

(12)

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

(13)

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

(14)

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’

(15)

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

(16)

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

(17)

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

(18)

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

(19)

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 

(20)

append Function

Str1.append(str2);

(21)
(22)

substr Function

We can extract one portion of a string with the

method substr.

This does not remove the portion from the original

(23)

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 

(24)

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

(25)

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 ");

(26)

String str1=“hello world”; String str2=“to this”

Str1.insert(pos1,str2,pos2,len2); Str1.insert(6,str2,0,3);

(27)

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

(28)

erase function

String s1 = “abc1234pqr”;S1.erase(3,5);

(29)

size & empty Function

String s1 = “abc”;

Cout<<s1.size();

Cout<<(s1.empty()? “True” : “false”)<<endl;

(30)

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++)

(31)

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

(32)

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";

(33)

Actually, you do not place the null character at the

end of a string constant. The C++ compiler

(34)

#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:

(35)
(36)

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;

(37)

Output:

Strcpy( str3, str1) : Hello

(38)

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

(39)

References

Related documents

A multidimensional combination of outstanding separation power is that of HPLC coupled with auto- mated multiple development planar chromatography featuring evaluation by a special

23(1)(d) The registered provider shall ensure that there is an annual review of the quality and safety of care and support in the designated centre and that such care

The direct memory access feature with the control and storage element permits high speed data transfer between memory and ex- ternal devices.. This access channel

RENEWAL SERIES PAPER 8.

Having shown that resveratrol treatment increased the expression of the mitochondrial biogenesis proteins (Figure 5.1), increased reserve capacity (Figure 5.3 B) and

Assessment scales for common symptoms often used in both early and advanced cancer (like the Edmonton Symptom Assessment Scale) do not include insomnia.. This is surprising,

This composition is an interesting one It has good power and is very inexpensive to manufacture One of the attractive properties of the explosive is its high cap sensitivity One

a) lnkl. Les données concernant Cuba ne sont contenues dans la somme « Camp socialiste» qu'à partir dt 1962.. us donnles concernant Cuba ne sont contenues dQ/1$/a somme