0% found this document useful (0 votes)
29 views19 pages

Lecture 10

Uploaded by

benivorentpeter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views19 pages

Lecture 10

Uploaded by

benivorentpeter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 19

COLLEGE OF INFORMATICS AND VIRTUAL EDUCATION

(CIVE)

CP123: Introduction to High-Level Programming

String Manipulation

1
C++ Strings
 A string is a sequence of characters.
 Two types of strings are supported by compilers:
 C-style strings: null-terminated(‘\0’) array of characters.
 C++ strings: object whose string type is defined in the
<string> library.
 You can convert C++ string into C-style string using
c_str() function:

string s = “ABCDEFG”;
const char* cs = s.c_str();
 The c_str() function has a return type const char*
2
C++ Strings
 Formatted Input: Stream extraction operator
 cin >> stringObject;
 the extraction operator >> formats the data that it receives
through its input stream; it skips over whitespace.
 Unformatted Input: getline function for a string
 getline( cin, s)
 does not skip over whitespace
 delimited by newline
 reads an entire line of characters into s

3
String Length
 Unlike numbers, strings are objects.
 The number of characters in a string is called the length of
the string.
 E.g., the length of “Tegeta Escrow Account!” is 22.
 Compute the length of the string with the length()
function:
 int n = name.length();
 Thus, can call functions on strings, e.g., name.length()

4
Indexing Strings
 Characters of a string are numbered with 0-based
indexes:
string mkday=“Mkwawa2014”;

0 1 2 3 4 5 6 7 8 9
M k w a w a 2 0 1 4

 The first character's index is always 0.


 The last character's index is 1 less than the string's length.
 The individual characters are values of type char.

5
Accessing Individual Characters
 Using square brackets, you can access individual characters
within a string as if it’s a char array.
 That is, you can read and write to characters within a string
using an index of particular character within [].
 Note that string indexes range from 0 to string length-1. Be
careful not to access positions outside the bounds of the
string.
 Syntax:
char charName=StringName[index];
 Example:
string courseID=“IS 142”;
char firstLetter=courseID[0] //accesses character ‘I’ 6
Accessing Individual Characters..
 You can also use the at() function to access
individual string characters:
 Example:
stringName.at(i)=‘A’;

 Is Equivalent to:
stringName[i]=‘A’;

7
Retrieving a Substring
 Function substr() retrieves a substring from a
given string.
 Syntax:

OriginalString.substr(startIndex,N)
 OriginalString: String from which a substring is to be
extracted.
 startIndex: first character to start retrieving.
 N: total number of characters to be retrieved.
 Example:
string name=“Mkwawa University College”;
string newName=name.substr(0,6); //Mkwawa 8
Comparing Two Strings
 Relational and Equality Operators are used to
compare two strings.
 The comparison is lexicographical, character by
character and is case-sensitive.
 The values of characters in the ASCII table
determines the result of comparison.
 For example the ASCII value for A is 65 and that of a
is 97, therefore a is greater than A.

9
Comparing Two Strings..
 Example:
string fruit1=“apple”;
string fruit2=“Apple”;

bool check1=(fruit1==fruit2) //false


bool check2=(fruit1!=fruit2) //true
bool check3=(fruit1>=fruit2) //true
bool check4=(fruit<fruit2) //false

10
String Concatenation
 One string can be appended to another by using a +
sign.
 Syntax:
newString=string1+string2;
 Example:
string courseID=“IS142”;
string colon=“:”;
string courseName=“High-Level Programming”;
string course=courseID+colon+courseName;
//IS142:High-Level Programming
11
Searching Within a String
 find() function is used to search for particular substring or
character in a given string.
 It returns the index of the first occurrence of a given
substring or character .
 If the item being searched is not in the given string, the
length of the string is displayed.
 Syntax:
int indx=stringName.find(searchedItem);
 Example:
string s7 = “Mississippi River basin”; //23 characters
cout << s7.find(“si”) << endl; //prints 3
cout << s7.find(“so”) << endl; //prints 23, the length of the string 12
Searching Within a String
 find() function has an optional integer argument
that allows you to specify the starting position
from which searching can begin.
 Syntax:

int indx=stringName.find(searchedItem,
startingIndex);
 Example:
string s7 = “Mississippi River basin”; //23 characters
cout << s7.find(“si”,4) << endl; //prints 6
13
String Modification
 String length or contents can be modified using these
functions:
 replace()
 insert()
 erase()

 Syntax for replace():


string newString=originalString.replace(startIndex,NoOfChars,newChars);
 Syntax for insert():
string newString=originalString.insert(startIndex, newChars);
 Inserts newChars before startIndex
14
String Modification..
 Syntax for erase():
string newString=originalString.erase(startIndex);
 Erase from startIndex to end of string, including
startIndex.
 Example:
string str = "this is an example string.";
string str3="sample phrase";

str.replace(19,6, str3, 7, 6); // "this is an example phrase."

15
Manipulation of Individual Characters
in a String
 C++ allows to manipulate individual characters in the
string using special functions available in various
libraries.
 An example of such libraries is ctype.h with following
functions:
 toupper() //converts a character to uppercase
 tolower() //converts a character to lowercase
 isupper() //checks if a character is in uppercase
 islower() //checks is a character is in lowercase
 isdigit() //checks is a character is a digit
16
Manipulation of Individual Characters
in a String..
 The ctype.h library need to be included in your program
before you can use any of its functions.
 An example of such libraries is ctype.h with following
functions:
 isalpha() //checks if a character is an alphabet
 isspace() //checks if a character is a whitespace or
//not-white space means tab or space
bar //character
 isalnum() //checks if a character is alphanumeric-
//that means alphabet or digit
17
Example One

18
Example Two

19

You might also like