SlideShare a Scribd company logo
Presentation on
Character Array & Strings
• Prepared by-
Tasnima Hamid
Program- Internet of Things (IoT)
Department- Information and Communication Technology (ICT)
Bangabandhu Sheikh Mujibur Rahman Digital University, Bangladesh.
Overview
▪ Character Array &
Strings
▪ Declaration of a string.
▪ Initialization of a string.
▪ Reading strings.
▪ Writing strings.
▪ String Functions
▪ Arithmetic Operations
Character Arrays and Strings and Their Uses
• A string is represented using a character array and is always
terminated with the null character ‘0’
• A string is a sequence of characters that is treated as a single
data item.
• Strings are actually one-dimensional array.
• Character strings are often used to build meaningful and readable
programs.
Memory Representation of String
Index
0 1 2 3 4 5 6 7 8 9 10 11
value
T E A M A M P H A N 0
Address
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
• 12 bytes of memory is allocated to store 12 characters.
Declaring
• C allows to represent strings as character arrays rather than
strings.
• A string variable is any valid C variable name and is always
declared as an array of characters.
• The general form of declaration of a string variable is
char string_name[ size ];
• Here, string_name is any name given to string variable and size
is used to define the length of the string or the number of
characters in the string.
• The size should be equal to the maximum numbers of characters
in the string plus one.
Initializing A String
• A string can be initialized in several ways
char str[ ] = “Team Amphan”;
char str[12] = “Team Amphan” ;
char str[ ] = {‘T’, ‘e’, ‘a’, ‘m’, ‘ ’, ‘A’, ‘m’, ‘p’, ‘h’, ‘a’, ‘n’, ‘0’ } ;
char str[12] = {‘T’, ‘e’, ‘a’, ‘m’, ‘ ’, ‘A’, ‘m’, ‘p’, ‘h’, ‘a’, ‘n’, ‘0’ } ;
Reading String from Terminal
• Strings can be read in several ways using-
scanf() getchar() gets() Line of Text
• Syntax-
char string_name [string_size];
scanf(“%ws”, string_name);
• %s and %ws can read only strings without whitespaces.
• Using getchar
char ch;
ch=getchar(); //no parameter
• Using gets
gets(str); //one parameter
• %[. .] can be used to read a line containing a variety of characters, including whitespaces.
• Using Line of Text
char a [80];
scanf(“%[^n]”, a);
Writing Strings to Screen
• Strings can be written in several ways using-
printf() putchar() puts()
• Using printf function
printf(“%s”, string_name);
• C uses putchar to output the values of character variables.
char ch =‘A’;
putchar (ch); equivalent to printf(“%c”, ch);
• Another convenient way of printing string values is to use the function
puts. puts(str);
Char str[12]=“Team Amphan”
9
String Handling Functions
The header file <string.h> contains many string manipulation
functions. Such as-
Function Name Function Action/Purpose
String Length strlen Get string length.
String Copy strcpy Copy a string.
String Concatenation strcat Concatenate two strings.
String Compare strcmp Compare two strings.
String Reverse strrev Return the string reversed.
Lower to Upper strupr Convert to upper case.
Upper to Lower strlwr Convert to lower case.
Character Existence strchr Searching a character.
String Length
• This function counts and returns the number of characters in a
string. The counting ends at the first null character.
int n = strlen(string);
String Copy
• Syntax-
strcpy(string1,string2);
Here, string1 is the destination string and string2 is the source
string.
strncpy(string1, string2, n);
This function copies only the left-most n characters of the
source string to the destination string.
Copying A String
Comparison of Two Strings
• Syntax-
strcmp(string1,string2);
Here, string1 is the destination string and string2 is the source string.
strncmp(string1, string2, n);
This function compares the left-most n characters of the source string
and the destination string and returns.
It returns integer value which includes(0,positive and negative).
• Decimal equivalent of ASCII code of a is 97
• Decimal equivalent of ASCII code of A is 65
• Decimal equivalent of ASCII code of 0 is 48
When return value is negative When return value is positive
Comparing Strings
• Syntax-
• strncmp(string1, string2, n);
String Concatenation
• Syntax-
strcat(string1,string2);
Here, string1 is the destination string and string2 is the source
string.
• It adds second string at the end of the first string.
strncat(string1, string2, n);
This function concatenates only the left-most n characters of
the source string at the end of destination string.
String Concatenation
Converting Cases
• Syntax
strupr(string_name);
This function converts the lower case letters of the string into upper case letters.
• Syntax
strlwr(string_name);
This function converts the upper case letters of the string into lower case letters.
String Reverse
• Syntax
strrev(string_name);
This function reverses the character string.
Character Existence in String
• It searches string string1 for character ch.
• strchr(string1, ‘ch’);
This function will locate the first occurrence of the character
‘ch’ and the call.
• strrchr(string1, ‘ch’);
This function will locate the last occurrence of the character
‘ch’ and the call.
Character Existence in String
String Subset
• Syntax
strstr(string1,string2);
• This function can be used to locate a sub-string in a string.
• This function searches the string string1 to see whether the
string string2 is contained in string1. If yes, the function
returns the position of the first occurrence of the sub-string.
Otherwise, it returns a null pointer.
Arithmetic Operations on Characters
• Way 1: Displays ASCII value[ Note that %d in Printf ]
char x = 'a’;
printf("%d",x); // Display Result = 97
• Way 2 : Displays Character value[ Note that %c in Printf ]
char x = ‘a’;
printf("%c",x); // Display Result = a
• Way 3 : Displays Next ASCII value[ Note that %d in Printf ]
char x = 'a' + 1 ;
printf("%d",x);// Display Result = 98 ( ascii of 'b' )
Arithmetic Operations on Characters
• Way 4 Displays Next Character value[Note that %c in Printf ]
char x = 'a' + 1;
printf("%c",x); // Display Result = 'b'
• Way 5 : Displays Difference between 2 ASCII in Integer[Note %d in Printf ]
char x = 'z' - 'a’;
printf("%d", x); /* Display Result = 25 (difference between ASCII of z and a ) */
• Way 6 : Displays Difference between 2 ASCII in Char [Note that %c in Printf ]
char x = 'z' - 'a';
printf("%c", x); /* Display Result = ↓ ( difference between ASCII of z and a ) */
• The C library supports a function that converts a string of digits into their integer
values.
x=atoi(string);
Arithmetic Operations on Characters
Thank You

More Related Content

What's hot

String in c programming
String in c programmingString in c programming
String in c programming
Devan Thakur
 
C string
C stringC string
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
Arrays in c
Arrays in cArrays in c
Arrays in c
CHANDAN KUMAR
 
Array in c
Array in cArray in c
Array in c
Ravi Gelani
 
Arrays in c
Arrays in cArrays in c
Arrays in c
Jeeva Nanthini
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
CGC Technical campus,Mohali
 
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++
Samsil Arefin
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
kashyap399
 
C Pointers
C PointersC Pointers
C Pointers
omukhtar
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in CJeya Lakshmi
 
String in c
String in cString in c
String in c
Suneel Dogra
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
P M Patil
 
Structure in c
Structure in cStructure in c
Structure in c
Prabhu Govind
 
Arrays In C Language
Arrays In C LanguageArrays In C Language
Arrays In C Language
Surbhi Yadav
 

What's hot (20)

Function in C program
Function in C programFunction in C program
Function in C program
 
String in c programming
String in c programmingString in c programming
String in c programming
 
C string
C stringC string
C string
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Strings
StringsStrings
Strings
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Array in c
Array in cArray in c
Array in c
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
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++
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
 
C Pointers
C PointersC Pointers
C Pointers
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
String in c
String in cString in c
String in c
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
 
Structure in c
Structure in cStructure in c
Structure in c
 
Arrays In C Language
Arrays In C LanguageArrays In C Language
Arrays In C Language
 

Similar to Character Array and String

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
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
ssusere19c741
 
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
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_
KarthicaMarasamy
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
Aliul Kadir Akib
 
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 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
 
Java Object Orientend Programming 1.pptx
Java Object Orientend Programming 1.pptxJava Object Orientend Programming 1.pptx
Java Object Orientend Programming 1.pptx
OmarBinkasimSefat
 
Strings
StringsStrings
Strings
Saranya saran
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
Sasideepa
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
Sasideepa
 
Module-2_Strings concepts in c programming
Module-2_Strings concepts in c programmingModule-2_Strings concepts in c programming
Module-2_Strings concepts in c programming
CHAITRAB29
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 

Similar to Character Array and String (20)

Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
 
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 MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
Java Object Orientend Programming 1.pptx
Java Object Orientend Programming 1.pptxJava Object Orientend Programming 1.pptx
Java Object Orientend Programming 1.pptx
 
Strings
StringsStrings
Strings
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
 
Team 1
Team 1Team 1
Team 1
 
Strings
StringsStrings
Strings
 
Module-2_Strings concepts in c programming
Module-2_Strings concepts in c programmingModule-2_Strings concepts in c programming
Module-2_Strings concepts in c programming
 
Strings
StringsStrings
Strings
 
Strings
StringsStrings
Strings
 
Strings
StringsStrings
Strings
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 

Recently uploaded

Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
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
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 

Recently uploaded (20)

Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
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
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 

Character Array and String

  • 1. Presentation on Character Array & Strings • Prepared by- Tasnima Hamid Program- Internet of Things (IoT) Department- Information and Communication Technology (ICT) Bangabandhu Sheikh Mujibur Rahman Digital University, Bangladesh.
  • 2. Overview ▪ Character Array & Strings ▪ Declaration of a string. ▪ Initialization of a string. ▪ Reading strings. ▪ Writing strings. ▪ String Functions ▪ Arithmetic Operations
  • 3. Character Arrays and Strings and Their Uses • A string is represented using a character array and is always terminated with the null character ‘0’ • A string is a sequence of characters that is treated as a single data item. • Strings are actually one-dimensional array. • Character strings are often used to build meaningful and readable programs.
  • 4. Memory Representation of String Index 0 1 2 3 4 5 6 7 8 9 10 11 value T E A M A M P H A N 0 Address 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 • 12 bytes of memory is allocated to store 12 characters.
  • 5. Declaring • C allows to represent strings as character arrays rather than strings. • A string variable is any valid C variable name and is always declared as an array of characters. • The general form of declaration of a string variable is char string_name[ size ]; • Here, string_name is any name given to string variable and size is used to define the length of the string or the number of characters in the string. • The size should be equal to the maximum numbers of characters in the string plus one.
  • 6. Initializing A String • A string can be initialized in several ways char str[ ] = “Team Amphan”; char str[12] = “Team Amphan” ; char str[ ] = {‘T’, ‘e’, ‘a’, ‘m’, ‘ ’, ‘A’, ‘m’, ‘p’, ‘h’, ‘a’, ‘n’, ‘0’ } ; char str[12] = {‘T’, ‘e’, ‘a’, ‘m’, ‘ ’, ‘A’, ‘m’, ‘p’, ‘h’, ‘a’, ‘n’, ‘0’ } ;
  • 7. Reading String from Terminal • Strings can be read in several ways using- scanf() getchar() gets() Line of Text • Syntax- char string_name [string_size]; scanf(“%ws”, string_name); • %s and %ws can read only strings without whitespaces. • Using getchar char ch; ch=getchar(); //no parameter • Using gets gets(str); //one parameter • %[. .] can be used to read a line containing a variety of characters, including whitespaces. • Using Line of Text char a [80]; scanf(“%[^n]”, a);
  • 8. Writing Strings to Screen • Strings can be written in several ways using- printf() putchar() puts() • Using printf function printf(“%s”, string_name); • C uses putchar to output the values of character variables. char ch =‘A’; putchar (ch); equivalent to printf(“%c”, ch); • Another convenient way of printing string values is to use the function puts. puts(str);
  • 10. String Handling Functions The header file <string.h> contains many string manipulation functions. Such as- Function Name Function Action/Purpose String Length strlen Get string length. String Copy strcpy Copy a string. String Concatenation strcat Concatenate two strings. String Compare strcmp Compare two strings. String Reverse strrev Return the string reversed. Lower to Upper strupr Convert to upper case. Upper to Lower strlwr Convert to lower case. Character Existence strchr Searching a character.
  • 11. String Length • This function counts and returns the number of characters in a string. The counting ends at the first null character. int n = strlen(string);
  • 12. String Copy • Syntax- strcpy(string1,string2); Here, string1 is the destination string and string2 is the source string. strncpy(string1, string2, n); This function copies only the left-most n characters of the source string to the destination string.
  • 14. Comparison of Two Strings • Syntax- strcmp(string1,string2); Here, string1 is the destination string and string2 is the source string. strncmp(string1, string2, n); This function compares the left-most n characters of the source string and the destination string and returns. It returns integer value which includes(0,positive and negative). • Decimal equivalent of ASCII code of a is 97 • Decimal equivalent of ASCII code of A is 65 • Decimal equivalent of ASCII code of 0 is 48
  • 15. When return value is negative When return value is positive
  • 16. Comparing Strings • Syntax- • strncmp(string1, string2, n);
  • 17. String Concatenation • Syntax- strcat(string1,string2); Here, string1 is the destination string and string2 is the source string. • It adds second string at the end of the first string. strncat(string1, string2, n); This function concatenates only the left-most n characters of the source string at the end of destination string.
  • 19. Converting Cases • Syntax strupr(string_name); This function converts the lower case letters of the string into upper case letters. • Syntax strlwr(string_name); This function converts the upper case letters of the string into lower case letters.
  • 20. String Reverse • Syntax strrev(string_name); This function reverses the character string.
  • 21. Character Existence in String • It searches string string1 for character ch. • strchr(string1, ‘ch’); This function will locate the first occurrence of the character ‘ch’ and the call. • strrchr(string1, ‘ch’); This function will locate the last occurrence of the character ‘ch’ and the call.
  • 23. String Subset • Syntax strstr(string1,string2); • This function can be used to locate a sub-string in a string. • This function searches the string string1 to see whether the string string2 is contained in string1. If yes, the function returns the position of the first occurrence of the sub-string. Otherwise, it returns a null pointer.
  • 24. Arithmetic Operations on Characters • Way 1: Displays ASCII value[ Note that %d in Printf ] char x = 'a’; printf("%d",x); // Display Result = 97 • Way 2 : Displays Character value[ Note that %c in Printf ] char x = ‘a’; printf("%c",x); // Display Result = a • Way 3 : Displays Next ASCII value[ Note that %d in Printf ] char x = 'a' + 1 ; printf("%d",x);// Display Result = 98 ( ascii of 'b' )
  • 25. Arithmetic Operations on Characters • Way 4 Displays Next Character value[Note that %c in Printf ] char x = 'a' + 1; printf("%c",x); // Display Result = 'b' • Way 5 : Displays Difference between 2 ASCII in Integer[Note %d in Printf ] char x = 'z' - 'a’; printf("%d", x); /* Display Result = 25 (difference between ASCII of z and a ) */ • Way 6 : Displays Difference between 2 ASCII in Char [Note that %c in Printf ] char x = 'z' - 'a'; printf("%c", x); /* Display Result = ↓ ( difference between ASCII of z and a ) */ • The C library supports a function that converts a string of digits into their integer values. x=atoi(string);