SlideShare uma empresa Scribd logo
1 de 11
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);

Mais conteúdo relacionado

Mais procurados

structure and union
structure and unionstructure and union
structure and union
student
 

Mais procurados (20)

Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
String in c programming
String in c programmingString in c programming
String in c programming
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
2D Array
2D Array 2D Array
2D Array
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 
Array in c#
Array in c#Array in c#
Array in c#
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
Strings
StringsStrings
Strings
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Strings in C
Strings in CStrings in C
Strings in C
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
String C Programming
String C ProgrammingString C Programming
String C Programming
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
structure and union
structure and unionstructure and union
structure and union
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 

Semelhante a Strings in c++

String & its application
String & its applicationString & its application
String & its application
Tech_MX
 

Semelhante a 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
 
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
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
 
Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
 
Ch09
Ch09Ch09
Ch09
 
Chapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfChapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdf
 
String & its application
String & its applicationString & its application
String & its application
 

Mais de International Islamic University

Mais de 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
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Último (20)

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.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);