SlideShare a Scribd company logo
1 of 19
Jeanine Ingber
Strings
•C strings
•string class
Jeanine Ingber
C Strings
 A C string is a sequence of characters,
terminated with a null character (‘0’)
 value of null is 0
 All C strings are assumed to be null
terminated
“This is a string” is an example of a string
constant. This constant is null terminated.
Jeanine Ingber
C string variables
 C++ has no built in string data type
 C strings are supported using a 1
dimensional array of characters.
 Since a string must be terminated by a null,
the size of a string variable (array of type
char) must be declared to hold to one
additional character (the ‘0’)
Jeanine Ingber
Declaring and Initializing C strings
 char string1[10];
– can hold 10 characters
– can hold a string of up to 9 characters in length
 char name[] = “Ingber”;
– name is declared to have size 7
– name is a C string
 char string2[10] = {‘t’, ‘o’, ‘m’};
– string2 is declared to have size 10
– string2 is not a C string
 char string3[10] = {‘s’, ‘u’, ‘e’, ‘0’};
– string3 is declared to have size 10
– string3 is a C string
Jeanine Ingber
Aggregate Operations
 Aggregate array assignment is not allowed in C++
char name[] = “Sue”; //valid initialization
char name2[10];
name2 = “Tom”; //not allowed
 C++ does support aggregate I/O for strings only
char name[] = “Jack”;
cout << name; //Jack is output
int numbers[10] = {1,2,3};
cout << numbers; //what will it output?
char string[5] = {‘h’,’e’, ‘l’, ‘l’, ‘o’};
cout << string; //what will it output?
Jeanine Ingber
String Input
 >>
– uses white space as a delimiter
– appends null to input string
– does not do any array bounds checking
 .getline(char* string, int limit, [char delim = ch])
– extracts a block of characters and places them in the
character array addressed by string
– extracts at most limit-1 characters
– appends the null character
– extracts less than limit-1 characters if end-of-file is reached
or delim character is reached
– by default, the delimiter is the newline (‘n’)
Jeanine Ingber
Examples using >>
char first[5], last[5];
cin >> first >> last;
cout << first << last;
input stream:
Mary Smith
first
last
Outut?
M a r y 0
S m i t h
Jeanine Ingber
>> example
char text_string[10];
cin >> text_string;
cout << text_string << endl;
cin.getline(text_string, 10);
cout << text_string << endl;
input stream
This is a line of text.
Output?
Jeanine Ingber
Examples using getline()
const int lineSize = 72;
int readin, lcnt=0;
char text_string[lineSize];
fin.getline(text_string, lineSize);
while(!fin.eof())
{
lcnt++;
readin = fin.gcount(); //returns the number of characters
//actually extracted by last call to getline()
cout << “Line #” << lcnt << “tChars read: “ << readin <<endl
<< text_string << endl;
fin.getline(text_string, lineSize);
} //sample of a few lines from a math text
Line #1 Chars read: 48
Mathematics is an expression of the human mind.
Line #2 Chars read: 57
It reflects the active will, the contemplative reason ..
Line #3 Chars read: 12
Never mind.
Jeanine Ingber
C String Functions
Defined in the header file string.h
 (=, <, >, ==) not defined for C strings
 strlen(str)
– returns integer length of string
– counts all characters up to but not including null
 strcmp(str1, str2)
– returns integer < 0 if str1 < str2
– returns integer == 0 if str1 == str2
– returns integer > 0 if str1 > str2
 strcpy(to_str, from_str)
– copies from_str including null into to_str
 strcat(str1,str2)
– append str2 to the end of str1
Jeanine Ingber
Function to Swap two C String
void Swap(char str1[], char str2[])
{
char temp[MAXLEN];
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
.
if(strcmp(str1,str2) > 0)
swap(str1, str2);
Jeanine Ingber
2-D Arrays of Char - Array of
Strings
char word_list[word_count][max_word_len];
cin >> word_list[0]; //read word and store in first row
strcpy(word_list[1], “Hello”);
H e l l o 0
Jeanine Ingber
String Class - include <string>
 string objects have two attributes
– the characters in the string
– the number of characters in a string
 string objects are not ‘0’ terminated
string message = “Hello”;
message
size
H e l l o
5
Jeanine Ingber
String I/O
 >>, <<
string name; //no size required
cin >> name; //uses white space as a delimiter
cout << name;
 getline()
string textline;
getline(cin, textline, ‘n’);
cout << textline;
Jeanine Ingber
String Operators
 Assignment (=)
 Concatenate (+)
 Append (+=)
#include <string>
.
int main()
{
string message1 = “Hello”, message2;
message2 = message1; //assignment
string name, first, last;
cin >> first >> last;
name = first + ‘ ‘ + last; //concatenation
message2 += “ there!”; //appending
cout << message2; //output is Hello there!
return 0;
}
Jeanine Ingber
String Functions
 size()
– returns the number of characters in a string
 substr(int start, int len)
– returns the sub-string of length len, beginning at start
 find(string sub_str, int start)
– returns the position of sub_str (or a very large number if sub_str is
not found)
– begins looking for sub_str at start
 c_str()
– converts string object to C string
Jeanine Ingber
#include <iostream>
#include <string>
using namespace std;
int main()
{
string date = “March 1, 1999”;
int i = date.size(); // i is assigned the value 13
string year;
year = date.substr(9,4);
cout << year << endl; //output is 1999
i = date.find(‘,’ , 0); // i is assigned 7
return 0;
}
Jeanine Ingber
Example - Palindromes
A palindrome is a word (noon) , sentence
(Draw a level award) or number (18781)
that reads the same backward or forward.
Write a function that takes a string as input
and determines if the string is a
palindrome. (Note: white space is ignored
when determining if a word, sentence or
number is a palindrome. All white space
has been removed from the input string.)
Jeanine Ingber
/*------------------------------------------------------------
-----*/
/* This function returns a value of 1 if string is a
palindrome. */
/* The function returns a value of 0 otherwise.
*/
int is_palindrome(char string[])
{
int is_pal, begin=0, end;
end = strlen(string) -1;
is_pal = 1;
while(is_pal && begin <=end)
{
if(string[begin] != string[end])
{
is_pal = 0;
}
begin++;
end--;
}
return(is_pal);
}
/*------------------------------------------------------------
---*/

More Related Content

Similar to Week7.ppt

CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
Sasideepa
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
Fahim Adil
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 

Similar to Week7.ppt (20)

CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
 
Unitii string
Unitii stringUnitii string
Unitii string
 
String handling
String handlingString handling
String handling
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
String in c programming
String in c programmingString in c programming
String in c programming
 
Team 1
Team 1Team 1
Team 1
 
Strings part2
Strings part2Strings part2
Strings part2
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
C++ Strings.ppt
C++ Strings.pptC++ Strings.ppt
C++ Strings.ppt
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
String notes
String notesString notes
String notes
 
14 strings
14 strings14 strings
14 strings
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 

More from JosManuel782430

More from JosManuel782430 (17)

sedra42021_appc.ppt
sedra42021_appc.pptsedra42021_appc.ppt
sedra42021_appc.ppt
 
IP1C - SCRATCH.pptx
IP1C - SCRATCH.pptxIP1C - SCRATCH.pptx
IP1C - SCRATCH.pptx
 
Caldeiras e vapor.pptx
Caldeiras e vapor.pptxCaldeiras e vapor.pptx
Caldeiras e vapor.pptx
 
01-Aco_Carbono_Ligas.ppt
01-Aco_Carbono_Ligas.ppt01-Aco_Carbono_Ligas.ppt
01-Aco_Carbono_Ligas.ppt
 
-Polynésie.ppt
-Polynésie.ppt-Polynésie.ppt
-Polynésie.ppt
 
Torneamento.pdf
Torneamento.pdfTorneamento.pdf
Torneamento.pdf
 
4-Hierarquia Digital.pptx
4-Hierarquia Digital.pptx4-Hierarquia Digital.pptx
4-Hierarquia Digital.pptx
 
4º Linguagem Algorítmica.pptx
4º Linguagem Algorítmica.pptx4º Linguagem Algorítmica.pptx
4º Linguagem Algorítmica.pptx
 
Autómatos Programáveis (1).pptx
Autómatos Programáveis (1).pptxAutómatos Programáveis (1).pptx
Autómatos Programáveis (1).pptx
 
1 IntroSOppt1.ppt
1 IntroSOppt1.ppt1 IntroSOppt1.ppt
1 IntroSOppt1.ppt
 
Week6.ppt
Week6.pptWeek6.ppt
Week6.ppt
 
X-25.ppt
X-25.pptX-25.ppt
X-25.ppt
 
70_modal_verbs.pptx
70_modal_verbs.pptx70_modal_verbs.pptx
70_modal_verbs.pptx
 
07-Polímeros.ppt
07-Polímeros.ppt07-Polímeros.ppt
07-Polímeros.ppt
 
Microcontroladores e Arduino.pptx
Microcontroladores e Arduino.pptxMicrocontroladores e Arduino.pptx
Microcontroladores e Arduino.pptx
 
sw9_past_perfect.pptx
sw9_past_perfect.pptxsw9_past_perfect.pptx
sw9_past_perfect.pptx
 
qualidade_e_fiabilidade.ppt
qualidade_e_fiabilidade.pptqualidade_e_fiabilidade.ppt
qualidade_e_fiabilidade.ppt
 

Recently uploaded

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
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
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
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
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
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

Week7.ppt

  • 2. Jeanine Ingber C Strings  A C string is a sequence of characters, terminated with a null character (‘0’)  value of null is 0  All C strings are assumed to be null terminated “This is a string” is an example of a string constant. This constant is null terminated.
  • 3. Jeanine Ingber C string variables  C++ has no built in string data type  C strings are supported using a 1 dimensional array of characters.  Since a string must be terminated by a null, the size of a string variable (array of type char) must be declared to hold to one additional character (the ‘0’)
  • 4. Jeanine Ingber Declaring and Initializing C strings  char string1[10]; – can hold 10 characters – can hold a string of up to 9 characters in length  char name[] = “Ingber”; – name is declared to have size 7 – name is a C string  char string2[10] = {‘t’, ‘o’, ‘m’}; – string2 is declared to have size 10 – string2 is not a C string  char string3[10] = {‘s’, ‘u’, ‘e’, ‘0’}; – string3 is declared to have size 10 – string3 is a C string
  • 5. Jeanine Ingber Aggregate Operations  Aggregate array assignment is not allowed in C++ char name[] = “Sue”; //valid initialization char name2[10]; name2 = “Tom”; //not allowed  C++ does support aggregate I/O for strings only char name[] = “Jack”; cout << name; //Jack is output int numbers[10] = {1,2,3}; cout << numbers; //what will it output? char string[5] = {‘h’,’e’, ‘l’, ‘l’, ‘o’}; cout << string; //what will it output?
  • 6. Jeanine Ingber String Input  >> – uses white space as a delimiter – appends null to input string – does not do any array bounds checking  .getline(char* string, int limit, [char delim = ch]) – extracts a block of characters and places them in the character array addressed by string – extracts at most limit-1 characters – appends the null character – extracts less than limit-1 characters if end-of-file is reached or delim character is reached – by default, the delimiter is the newline (‘n’)
  • 7. Jeanine Ingber Examples using >> char first[5], last[5]; cin >> first >> last; cout << first << last; input stream: Mary Smith first last Outut? M a r y 0 S m i t h
  • 8. Jeanine Ingber >> example char text_string[10]; cin >> text_string; cout << text_string << endl; cin.getline(text_string, 10); cout << text_string << endl; input stream This is a line of text. Output?
  • 9. Jeanine Ingber Examples using getline() const int lineSize = 72; int readin, lcnt=0; char text_string[lineSize]; fin.getline(text_string, lineSize); while(!fin.eof()) { lcnt++; readin = fin.gcount(); //returns the number of characters //actually extracted by last call to getline() cout << “Line #” << lcnt << “tChars read: “ << readin <<endl << text_string << endl; fin.getline(text_string, lineSize); } //sample of a few lines from a math text Line #1 Chars read: 48 Mathematics is an expression of the human mind. Line #2 Chars read: 57 It reflects the active will, the contemplative reason .. Line #3 Chars read: 12 Never mind.
  • 10. Jeanine Ingber C String Functions Defined in the header file string.h  (=, <, >, ==) not defined for C strings  strlen(str) – returns integer length of string – counts all characters up to but not including null  strcmp(str1, str2) – returns integer < 0 if str1 < str2 – returns integer == 0 if str1 == str2 – returns integer > 0 if str1 > str2  strcpy(to_str, from_str) – copies from_str including null into to_str  strcat(str1,str2) – append str2 to the end of str1
  • 11. Jeanine Ingber Function to Swap two C String void Swap(char str1[], char str2[]) { char temp[MAXLEN]; strcpy(temp, str1); strcpy(str1, str2); strcpy(str2, temp); } . if(strcmp(str1,str2) > 0) swap(str1, str2);
  • 12. Jeanine Ingber 2-D Arrays of Char - Array of Strings char word_list[word_count][max_word_len]; cin >> word_list[0]; //read word and store in first row strcpy(word_list[1], “Hello”); H e l l o 0
  • 13. Jeanine Ingber String Class - include <string>  string objects have two attributes – the characters in the string – the number of characters in a string  string objects are not ‘0’ terminated string message = “Hello”; message size H e l l o 5
  • 14. Jeanine Ingber String I/O  >>, << string name; //no size required cin >> name; //uses white space as a delimiter cout << name;  getline() string textline; getline(cin, textline, ‘n’); cout << textline;
  • 15. Jeanine Ingber String Operators  Assignment (=)  Concatenate (+)  Append (+=) #include <string> . int main() { string message1 = “Hello”, message2; message2 = message1; //assignment string name, first, last; cin >> first >> last; name = first + ‘ ‘ + last; //concatenation message2 += “ there!”; //appending cout << message2; //output is Hello there! return 0; }
  • 16. Jeanine Ingber String Functions  size() – returns the number of characters in a string  substr(int start, int len) – returns the sub-string of length len, beginning at start  find(string sub_str, int start) – returns the position of sub_str (or a very large number if sub_str is not found) – begins looking for sub_str at start  c_str() – converts string object to C string
  • 17. Jeanine Ingber #include <iostream> #include <string> using namespace std; int main() { string date = “March 1, 1999”; int i = date.size(); // i is assigned the value 13 string year; year = date.substr(9,4); cout << year << endl; //output is 1999 i = date.find(‘,’ , 0); // i is assigned 7 return 0; }
  • 18. Jeanine Ingber Example - Palindromes A palindrome is a word (noon) , sentence (Draw a level award) or number (18781) that reads the same backward or forward. Write a function that takes a string as input and determines if the string is a palindrome. (Note: white space is ignored when determining if a word, sentence or number is a palindrome. All white space has been removed from the input string.)
  • 19. Jeanine Ingber /*------------------------------------------------------------ -----*/ /* This function returns a value of 1 if string is a palindrome. */ /* The function returns a value of 0 otherwise. */ int is_palindrome(char string[]) { int is_pal, begin=0, end; end = strlen(string) -1; is_pal = 1; while(is_pal && begin <=end) { if(string[begin] != string[end]) { is_pal = 0; } begin++; end--; } return(is_pal); } /*------------------------------------------------------------ ---*/