SlideShare a Scribd company logo
STRINGS in C++
SUNAWAR KHAN
MCS, MS(CS)
Strings
Strings are a fundamental concept, but they are not a built-in data type in C/C++.
String is collection of characters.
C-Strings
◦ C-style string: character array terminated by first null character.
◦ Wide string: wide character array terminated by first null character.
C++ - Strings
◦ Several Classes
◦ Standard Template Class:
◦ std::basic_string, std::string, std::wstring
No inter-operability between C and C++ style strings.
String example
C-string
◦ Array of chars that is null terminated (‘0’).
C++ - string
• Object whose string type is defined in the <string> file has a large repertoire of functions (e.g. length,
replace, etc.)
char cs[ ] = “Napoleon”; // C-string
string s = “Napoleon”; // C++ - string
cout << s << “ has “ << s.length() << “ characters.n”;
s.replace(5, 2,”ia”); //changes s to “Napolian
Strings
C-style strings consist of a contiguous sequence of characters
terminated by and including the first null character.
◦ A pointer to a string points to its initial character.
◦ The length of a string is the number of bytes preceding the null character
◦ The value of a string is the sequence of the values of the contained characters,
in order.
h e l l o 0
length
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
string s = “ABCDEFG”;
getline(cin, s); //reads entire line of characters into s
char c = s[2]; //assigns ‘C’ to c
S[4] = ‘*’; //changes s to “ABCD*FG”
strings
Common Errors:
Unbounded
string copies
Null-
termination
errors
Truncation
Write outside
array bounds
Off-by-one
errors
Improper data
sanitization
7
Functions
Character Macro Description
isalpha Returns true (a nonzero number) if the argument is a letter of the
alphabet. Returns 0 if the argument is not a letter.
isalnum Returns true (a nonzero number) if the argument is a letter of the
alphabet or a digit. Otherwise it returns 0.
isdigit Returns true (a nonzero number) if the argument is a digit 0–9.
Otherwise it returns 0.
islower Returns true (a nonzero number) if the argument is a lowercase
letter. Otherwise, it returns 0.
isprint Returns true (a nonzero number) if the argument is a printable
character (including a space). Returns 0 otherwise.
ispunct Returns true (a nonzero number) if the argument is a printable
character other than a digit, letter, or space. Returns 0
otherwise.
isupper Returns true (a nonzero number) if the argument is an uppercase
letter. Otherwise, it returns 0.
isspace Returns true (a nonzero number) if the argument is a whitespace
character. Whitespace characters are any of the following:
Program Code(ACSII)
// This program demonstrates some of the character testing
// functions.
#include <iostream.h>
#include <ctype.h>
void main(void)
{
char input;
cout << "Enter any character: ";
cin.get(input);
cout << "The character you entered is: " << input << endl;
cout << "Its ASCII code is: " << int(input) << endl;
if (isalpha(input))
cout << "That's an alphabetic character.n";
if (isdigit(input))
cout << "That's a numeric digit.n";
if (islower(input))
cout << "The letter you entered is lowercase.n";
if (isupper(input))
cout << "The letter you entered is uppercase.n";
if (isspace(input))
cout << "That's a whitespace character.n";
}
Enter any character: A
The character you entered is: A
Its ASCII code is: 65
That's an alphabetic character.
The letter you entered is uppercase.
OUTPUT
Enter any character: 7 [Enter]
The character you entered is: 7
Its ASCII code is: 55
That's a numeric digit.
OUTPUT
9
Character Case Conversion
The C++ library offers functions for converting a character to upper or lower case.
◦ Be sure to include ctype.h header file
Function Description
toupper Returns the uppercase equivalent of its argument.
tolower Returns the lowercase equivalent of its argument.
10
Sample Code
// This program calculates the area of a circle. It asks the
// user if he or she wishes to continue. A loop that
// demonstrates the toupper function repeats until the user
// enters 'y', 'Y', 'n', or 'N'.
#include <iostream.h>
#include <ctype.h>
void main(void)
{
const float pi = 3.14159;
float radius;
char go;
cout << "This program calculates the area of a circle.n";
cout.precision(2);
cout.setf(ios::fixed);
do
{
cout << "Enter the circle's radius: ";
cin >> radius;
cout << "The area is " << (pi * radius * radius);
cout << endl;
do
{
cout << "Calculate another? (Y or N) ";
cin >> go;
} while (toupper(go) != 'Y' && toupper(go) != 'N');
} while (toupper(go) == 'Y');
}
Enter the circle's radius: 10
The area is 314.16
Calculate another? (Y or N) b
Calculate another? (Y or N) y
Enter the circle's radius: 1
The area is 3.14
Calculate another? (Y or N) n
OUTPUT
11
String Function
Function Description
strlen Accepts a C-string or a pointer to a string as an argument. Returns the length of the
string (not including the null terminator. Example Usage: len = strlen(name);
strcat Accepts two C-strings or pointers to two strings as arguments. The function appends
the contents of the second string to the first string. (The first string is altered, the
second string is left unchanged.) Example Usage: strcat(string1, string2);
strcpy Accepts two C-strings or pointers to two strings as arguments. The function copies
the second string to the first string. The second string is left unchanged. Example
Usage: strcpy(string1, string2);
strncpy Accepts two C-strings or pointers to two strings and an integer argument. The third
argument, an integer, indicates how many characters to copy from the second string
to the first string. If the string2 has fewer than n characters, string1 is padded with
'0' characters. Example Usage: strncpy(string1, string2, n);
strcmp Accepts two C-strings or pointers to two string arguments. If string1 and string2are
the same, this function returns 0. If string2 is alphabetically greater than string1, it
returns a negative number. If string2 is alphabetically less than string1, it returns a
positive number. Example Usage: if (strcmp(string1, string2))
strstr Accepts two C-strings or pointers to two C-strings as arguments, searches for the
first occurrence of string2 in string1. If an occurrence of string2 is found, the
function returns a pointer to it. Otherwise, it returns a NULL pointer (address 0).
Example Usage: cout << strstr(string1, string2);

More Related Content

What's hot

C functions
C functionsC functions
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
Abdul Rehman
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
Vishesh Jha
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Nested loops
Nested loopsNested loops
Nested loops
Neeru Mittal
 
Function in C
Function in CFunction in C
Function in C
Dr. Abhineet Anand
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
Hashim Hashim
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
Rajab Ali
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
tanmaymodi4
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Java Tokens
Java  TokensJava  Tokens
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 

What's hot (20)

C functions
C functionsC functions
C functions
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Nested loops
Nested loopsNested loops
Nested loops
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Function in C
Function in CFunction in C
Function in C
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 

Similar to Strings in c++

STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
string in C
string in Cstring in C
String notes
String notesString notes
String notes
Prasadu Peddi
 
C string
C stringC string
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
Azeemaj101
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
OluwafolakeOjo
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
Appili Vamsi Krishna
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
strings
stringsstrings
strings
teach4uin
 
Strings
StringsStrings
Strings
Dhiviya Rose
 
Python data handling
Python data handlingPython data handling
Python data handling
Prof. Dr. K. Adisesha
 
Strings
StringsStrings
Strings
Saranya saran
 
lecture-5 string.pptx
lecture-5 string.pptxlecture-5 string.pptx
lecture-5 string.pptx
DilanAlmsa
 
Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
Jesmin Akhter
 

Similar to Strings in c++ (20)

STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
string in C
string in Cstring in C
string in C
 
String notes
String notesString notes
String notes
 
C string
C stringC string
C string
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
Strings in c
Strings in cStrings in c
Strings in c
 
strings
stringsstrings
strings
 
Strings
StringsStrings
Strings
 
Python data handling
Python data handlingPython data handling
Python data handling
 
Strings
StringsStrings
Strings
 
lecture-5 string.pptx
lecture-5 string.pptxlecture-5 string.pptx
lecture-5 string.pptx
 
Strings
StringsStrings
Strings
 
Strings
StringsStrings
Strings
 
Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
 

More from International Islamic University

Hash tables
Hash tablesHash tables
Binary Search Tree
Binary Search TreeBinary Search Tree
Graph 1
Graph 1Graph 1
Graph 2
Graph 2Graph 2
Graph 3
Graph 3Graph 3
Greedy algorithm
Greedy algorithmGreedy algorithm
Dynamic programming
Dynamic programmingDynamic programming
Quick sort
Quick sortQuick sort
Merge sort
Merge sortMerge sort
Linear timesorting
Linear timesortingLinear timesorting
Facial Expression Recognitino
Facial Expression RecognitinoFacial Expression Recognitino
Facial Expression Recognitino
International Islamic University
 
Data transmission
Data transmissionData transmission
Basic organization of computer
Basic organization of computerBasic organization of computer
Basic organization of computer
International Islamic University
 
Sorting techniques
Sorting techniquesSorting techniques

More from International Islamic University (20)

Hash tables
Hash tablesHash tables
Hash tables
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Graph 1
Graph 1Graph 1
Graph 1
 
Graph 2
Graph 2Graph 2
Graph 2
 
Graph 3
Graph 3Graph 3
Graph 3
 
Greedy algorithm
Greedy algorithmGreedy algorithm
Greedy algorithm
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Quick sort
Quick sortQuick sort
Quick sort
 
Merge sort
Merge sortMerge sort
Merge sort
 
Linear timesorting
Linear timesortingLinear timesorting
Linear timesorting
 
Facial Expression Recognitino
Facial Expression RecognitinoFacial Expression Recognitino
Facial Expression Recognitino
 
Lecture#4
Lecture#4Lecture#4
Lecture#4
 
Lecture#3
Lecture#3 Lecture#3
Lecture#3
 
Lecture#2
Lecture#2 Lecture#2
Lecture#2
 
Case study
Case studyCase study
Case study
 
Arrays
ArraysArrays
Arrays
 
Pcb
PcbPcb
Pcb
 
Data transmission
Data transmissionData transmission
Data transmission
 
Basic organization of computer
Basic organization of computerBasic organization of computer
Basic organization of computer
 
Sorting techniques
Sorting techniquesSorting techniques
Sorting techniques
 

Recently uploaded

MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 

Recently uploaded (20)

MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 

Strings in c++

  • 1. STRINGS in C++ SUNAWAR KHAN MCS, MS(CS)
  • 2. Strings Strings are a fundamental concept, but they are not a built-in data type in C/C++. String is collection of characters. C-Strings ◦ C-style string: character array terminated by first null character. ◦ Wide string: wide character array terminated by first null character. C++ - Strings ◦ Several Classes ◦ Standard Template Class: ◦ std::basic_string, std::string, std::wstring No inter-operability between C and C++ style strings.
  • 3. String example C-string ◦ Array of chars that is null terminated (‘0’). C++ - string • Object whose string type is defined in the <string> file has a large repertoire of functions (e.g. length, replace, etc.) char cs[ ] = “Napoleon”; // C-string string s = “Napoleon”; // C++ - string cout << s << “ has “ << s.length() << “ characters.n”; s.replace(5, 2,”ia”); //changes s to “Napolian
  • 4. Strings C-style strings consist of a contiguous sequence of characters terminated by and including the first null character. ◦ A pointer to a string points to its initial character. ◦ The length of a string is the number of bytes preceding the null character ◦ The value of a string is the sequence of the values of the contained characters, in order. h e l l o 0 length
  • 5. 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 string s = “ABCDEFG”; getline(cin, s); //reads entire line of characters into s char c = s[2]; //assigns ‘C’ to c S[4] = ‘*’; //changes s to “ABCD*FG”
  • 6. strings Common Errors: Unbounded string copies Null- termination errors Truncation Write outside array bounds Off-by-one errors Improper data sanitization
  • 7. 7 Functions Character Macro Description isalpha Returns true (a nonzero number) if the argument is a letter of the alphabet. Returns 0 if the argument is not a letter. isalnum Returns true (a nonzero number) if the argument is a letter of the alphabet or a digit. Otherwise it returns 0. isdigit Returns true (a nonzero number) if the argument is a digit 0–9. Otherwise it returns 0. islower Returns true (a nonzero number) if the argument is a lowercase letter. Otherwise, it returns 0. isprint Returns true (a nonzero number) if the argument is a printable character (including a space). Returns 0 otherwise. ispunct Returns true (a nonzero number) if the argument is a printable character other than a digit, letter, or space. Returns 0 otherwise. isupper Returns true (a nonzero number) if the argument is an uppercase letter. Otherwise, it returns 0. isspace Returns true (a nonzero number) if the argument is a whitespace character. Whitespace characters are any of the following:
  • 8. Program Code(ACSII) // This program demonstrates some of the character testing // functions. #include <iostream.h> #include <ctype.h> void main(void) { char input; cout << "Enter any character: "; cin.get(input); cout << "The character you entered is: " << input << endl; cout << "Its ASCII code is: " << int(input) << endl; if (isalpha(input)) cout << "That's an alphabetic character.n"; if (isdigit(input)) cout << "That's a numeric digit.n"; if (islower(input)) cout << "The letter you entered is lowercase.n"; if (isupper(input)) cout << "The letter you entered is uppercase.n"; if (isspace(input)) cout << "That's a whitespace character.n"; } Enter any character: A The character you entered is: A Its ASCII code is: 65 That's an alphabetic character. The letter you entered is uppercase. OUTPUT Enter any character: 7 [Enter] The character you entered is: 7 Its ASCII code is: 55 That's a numeric digit. OUTPUT
  • 9. 9 Character Case Conversion The C++ library offers functions for converting a character to upper or lower case. ◦ Be sure to include ctype.h header file Function Description toupper Returns the uppercase equivalent of its argument. tolower Returns the lowercase equivalent of its argument.
  • 10. 10 Sample Code // This program calculates the area of a circle. It asks the // user if he or she wishes to continue. A loop that // demonstrates the toupper function repeats until the user // enters 'y', 'Y', 'n', or 'N'. #include <iostream.h> #include <ctype.h> void main(void) { const float pi = 3.14159; float radius; char go; cout << "This program calculates the area of a circle.n"; cout.precision(2); cout.setf(ios::fixed); do { cout << "Enter the circle's radius: "; cin >> radius; cout << "The area is " << (pi * radius * radius); cout << endl; do { cout << "Calculate another? (Y or N) "; cin >> go; } while (toupper(go) != 'Y' && toupper(go) != 'N'); } while (toupper(go) == 'Y'); } Enter the circle's radius: 10 The area is 314.16 Calculate another? (Y or N) b Calculate another? (Y or N) y Enter the circle's radius: 1 The area is 3.14 Calculate another? (Y or N) n OUTPUT
  • 11. 11 String Function Function Description strlen Accepts a C-string or a pointer to a string as an argument. Returns the length of the string (not including the null terminator. Example Usage: len = strlen(name); strcat Accepts two C-strings or pointers to two strings as arguments. The function appends the contents of the second string to the first string. (The first string is altered, the second string is left unchanged.) Example Usage: strcat(string1, string2); strcpy Accepts two C-strings or pointers to two strings as arguments. The function copies the second string to the first string. The second string is left unchanged. Example Usage: strcpy(string1, string2); strncpy Accepts two C-strings or pointers to two strings and an integer argument. The third argument, an integer, indicates how many characters to copy from the second string to the first string. If the string2 has fewer than n characters, string1 is padded with '0' characters. Example Usage: strncpy(string1, string2, n); strcmp Accepts two C-strings or pointers to two string arguments. If string1 and string2are the same, this function returns 0. If string2 is alphabetically greater than string1, it returns a negative number. If string2 is alphabetically less than string1, it returns a positive number. Example Usage: if (strcmp(string1, string2)) strstr Accepts two C-strings or pointers to two C-strings as arguments, searches for the first occurrence of string2 in string1. If an occurrence of string2 is found, the function returns a pointer to it. Otherwise, it returns a NULL pointer (address 0). Example Usage: cout << strstr(string1, string2);