SlideShare a Scribd company logo
Strings
A string is a sequence of characters treated as a group. Any group of
characters defined between double quotation marks is a string constant.
We have already used some string literals:
“filename”
“output string”
Character strings are often used to build meaningful and readable programs.
Strings are important in many programming contexts:
names
other objects (numbers, identifiers, etc.)
Operations on strings include: Reading and writing strings, combining
strings together, copying one string to another, comparing strings for
equality, extracting a portion of a string.
Outline
Strings
Representation in C
String Literals
String Variables
String Input/Output
printf, scanf, gets, fgets, puts, fputs
String Functions
strlen, strcpy, strncpy, strcmp, strncmp, strcat, strncat, strchr, strrchr,
strstr, strspn, strcspn, strtok
Reading from/Printing to Strings
sprintf, sscanf
Strings in C
No explicit type, instead strings are maintained as arrays of
characters
Representing strings in C
 stored in arrays of characters
 array can be of any length
 end of string is indicated by a delimiter, the zero character ‘0’
"AString" A 0gnirtS
String Literals
String literal values are represented by sequences of
characters between double quotes (“)
Examples
“” - empty string
“hello”
“a” versus ‘a’
‘a’ is a single character value (stored in 1 byte) as the
ASCII value for a
“a” is an array with two characters, the first is a, the second
is the character value 0
Duplicate String Literals
Each string literal in a C program is stored at a
different location
So even if the string literals contain the same string,
they are not equal (in the == sense)
Example:
char string1[6] = “hello”;
char string2[6] = “hello”;
but string1 does not equal string2 (they are stored at
different locations)
Declaring and Initializing String Variables
Allocate an array of a size large enough to hold the string (plus 1 extra value
for the delimiter)
Char string_name[size];
Example: char city[10];
Examples (with initialization):
char str1[6] = “Hello”;
char str2[] = “Hello”;
char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’0’};
Note, each variable is considered a constant in that the space it is connected
to cannot be changed
str1 = str2; /* not allowable, but we can copy the contents
of str2 to str1 (more later) */
• When the compiler assigns a character string to a
character array it automatically supplies a NULL (o)
character at the end of the string.
We can declare the size much larger than the string size in the initializer.
That is the statement:
char str [10]=“GOOD”; is permitted.
However the following declaration is illegal. Char str2[3]=“Good”; This
will result in compile time error.
We cannot separate the initialization from declaration. i.e. char str3[5];
str3=“Good”;
Similarly, char s1[4]=“abc”;
cahr s2[4];
s2=s1; is not allowed. An array name cannot be used as the left
operand of the assignment operator.
“Why do we need a terminating NULL
character?”
A string is not a datatype in C but it is considered a data
structure stored in an array. The string is a variable length
structure and is stored in a fixed length array. The array
size is not always the size of the string and most often it is
much larger than the string stored in it. Therefore, the last
element of the array need not represent the end of the
string. We need some way to determine the end of the
string data and the NULL character serves as the “end of
string”.
Changing String Variables
Can change parts of a string variable
char str1[6] = “hello”;
str1[0] = ‘y’;
/* str1 is now “yello” */
str1[4] = ‘0’;
/* str1 is now “yell” */
Important to retain delimiter (replacing str1[5] in the
original string with something other than ‘0’ makes a
string that does not end)
Have to stay within limits of array
Reading Strings from terminal
Use %s field specification in scanf to read string:
ignores leading white space
reads characters until next white space encountered
C stores null (0) char after last non-white space character.
Example:
char Name[11];
scanf(“%s”,Name);
‘&’ is not required before the variable name. The unused
locations are filled with garbage.
We can also specify the field width using the form %ws in the
scanf statement for reading a specified number of characters
from the input string. Ex: scanf(“%ws”, name);
Reading Strings from terminal(cont)
Can use the width value in the field specification to
limit the number of characters read:
char Name[11];
scanf(“%10s”,Name);
Remember, you need one space for the 0
width should be one less than size of array
Strings shorter than the field specification are read
normally, but C always stops after reading 10
characters
Reading Strings from terminal(cont)
%s and %ws can read strings without white spaces i.e.
they cannot be used for reading a text containing more
than one word. However we can use the following code to
read a line:
char line[80];
scanf(“[^n]”, line);
printf(“%s”, line);
String Output
Use %s field specification in printf:
characters in string printed until 0 encountered
char Name[10] = “Rich”;
printf(“|%s|”,Name); /* outputs |Rich| */
Can use width value to print string in space:
printf(“|%10s|”,Name); /* outputs | Rich| */
Use - flag to left justify:
printf(“|%-10s|”,Name); /* outputs |Rich | */
Arithmetic operations on characters
Whenever a character constant or character variable is
used in an expression, it is automatically converted into an
integer value by the system.
Example: x=‘a’; printf(“%dn”,x); will display 97 on
screen which is ASCII value of ‘a’ in lower case.
Ex-2 x=‘z’-1 will assign value 121 to variable x.
Ex-3 ch>=‘A’ && ch<=‘Z’ would test whether the
character contained in variable ch is an upper case letter.
C has a function “atoi” that converts a string of digits into
their integer values. It is stored in <stdlib.h> Ex:
number=“1988”;
year=atoi(number);
Putting strings together
The process of combining two strings together is called
concatenation.
String3=string1+string2; is not valid.
We can combine the strings using the following program:
include <stdio.h>
int main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2); // calculate the length of string s1 // and store it in i
for(i = 0; s1[i] != '0'; ++i);
for(j = 0; s2[j] != '0'; ++j, ++i)
{ s1[i] = s2[j]; }
s1[i] = '0';
printf("After concatenation: %s", s1);
return 0;
}
String Copy:
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i = 0; s1[i] != '0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '0';
printf("String s2: %s", s2);
return 0;
}
ASSIGNMENT
WAP to compare two strings without using string
manipulation functions.
The most common functions used
from the library are:
1. strlen("name of string")
2. strcpy( dest, source)
3. strcmp( string1, string2 )
4. strstr( str1, str2 )
Declaration and usage of strlen() function
It is one of the most useful functions used from this
library, whenever we need the length of the string say
"str1"
we write it as
int len;
len = strlen(str1);
len will be the length of the string "str1".(it will include
all the spaces and characters in the string except the
NULL('0') character.
strlen( string )
strcpy() function
strcpy( dest, source)
This function copies the string "source" to string "dest".
Declaration
strcpy( str2, str1 );
strcmp( str1, str2 )
This function is used to compare two strings "str1" and
"str2". this function returns zero("0") if the two compared
strings are equal, else some none zero integer.
Declaration and usage of strcmp() function
strcmp( str1 , str2 ); //declaration
if( strcmp( str1, str2 )==0)
{ printf("string %s and string %s are equaln",str1,str2); }
else printf("string %s and string %s are not
equaln",str1,str2);
Return value
- if Return value if < 0 then it indicates str1 is less than str2
- if Return value if > 0 then it indicates str2 is less than str1
- if Return value if = 0 then it indicates str1 is equal to str2
strstr(str1, str2)
This library function finds the first occurrence of the substring str2
in the string str1. The terminating '0' character is not compared.
Declaration
strstr( str1, str2); - str1: the main string to be scanned. - str2: the
small string to be searched in str1.
// let say str2="speed"; //function can also be written as strstr(str1,
"speed" );
This function is very useful in checking whether str2 is a substring
of str1 or not.
Return value
This function returns a pointer to the first occurrence in str1 of any
of the entire sequence of characters specified in str2, or a NULL
pointer if the sequence is not present in str1.
Strcat()
Used for string concatenation(joining)
It takes two arguments i.e. 2 strings
Syntax: strcat(string1,string2);
After concatenation the resultant string is stored in first
string.
Exercise: WAP to input two strings, concatenate it and
print the resultant string.
Ad

More Related Content

What's hot (20)

C tokens
C tokensC tokens
C tokens
Manu1325
 
C string
C stringC string
C string
University of Potsdam
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
savitamhaske
 
structure and union
structure and unionstructure and union
structure and union
student
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Pointer in c
Pointer in cPointer in c
Pointer in c
lavanya marichamy
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
String functions in C
String functions in CString functions in C
String functions in C
baabtra.com - No. 1 supplier of quality freshers
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 
Type conversion
Type  conversionType  conversion
Type conversion
PreethaPreetha5
 
Modular programming
Modular programmingModular programming
Modular programming
Mohanlal Sukhadia University (MLSU)
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
programming9
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 

Similar to Strings (20)

unit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentationunit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
[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
 
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
 
Unitii string
Unitii stringUnitii string
Unitii string
Sowri Rajan
 
String notes
String notesString notes
String notes
Prasadu Peddi
 
Array &strings
Array &stringsArray &strings
Array &strings
UMA PARAMESWARI
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPTCfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
UNIT 4C-Strings.pptx for c language and basic knowledge
UNIT 4C-Strings.pptx for c language and basic knowledgeUNIT 4C-Strings.pptx for c language and basic knowledge
UNIT 4C-Strings.pptx for c language and basic knowledge
2024163103shubham
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
ChapterabcdefghijklmnopqrdstuvwxydanniipoChapterabcdefghijklmnopqrdstuvwxydanniipo
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
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
 
14 strings
14 strings14 strings
14 strings
Rohit Shrivastava
 
Principals of Programming in CModule -5.pdfModule-4.pdf
Principals of Programming in CModule -5.pdfModule-4.pdfPrincipals of Programming in CModule -5.pdfModule-4.pdf
Principals of Programming in CModule -5.pdfModule-4.pdf
anilcsbs
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
 
PROBLEM SOLVING USING A PPSC- UNIT -3.pdf
PROBLEM SOLVING USING A PPSC- UNIT -3.pdfPROBLEM SOLVING USING A PPSC- UNIT -3.pdf
PROBLEM SOLVING USING A PPSC- UNIT -3.pdf
JNTUK KAKINADA
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
웅식 전
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
Rumman Ansari
 
Strings
StringsStrings
Strings
Imad Ali
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
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
 
Strings part2
Strings part2Strings part2
Strings part2
yndaravind
 
unit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentationunit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
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
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPTCfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
UNIT 4C-Strings.pptx for c language and basic knowledge
UNIT 4C-Strings.pptx for c language and basic knowledgeUNIT 4C-Strings.pptx for c language and basic knowledge
UNIT 4C-Strings.pptx for c language and basic knowledge
2024163103shubham
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
ChapterabcdefghijklmnopqrdstuvwxydanniipoChapterabcdefghijklmnopqrdstuvwxydanniipo
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
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
 
Principals of Programming in CModule -5.pdfModule-4.pdf
Principals of Programming in CModule -5.pdfModule-4.pdfPrincipals of Programming in CModule -5.pdfModule-4.pdf
Principals of Programming in CModule -5.pdfModule-4.pdf
anilcsbs
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
 
PROBLEM SOLVING USING A PPSC- UNIT -3.pdf
PROBLEM SOLVING USING A PPSC- UNIT -3.pdfPROBLEM SOLVING USING A PPSC- UNIT -3.pdf
PROBLEM SOLVING USING A PPSC- UNIT -3.pdf
JNTUK KAKINADA
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
웅식 전
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
Rumman Ansari
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
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
 
Ad

More from Mitali Chugh (20)

Loc and function point
Loc and function pointLoc and function point
Loc and function point
Mitali Chugh
 
Unit1
Unit1Unit1
Unit1
Mitali Chugh
 
Unit 2 ppt
Unit 2 pptUnit 2 ppt
Unit 2 ppt
Mitali Chugh
 
Module 4
Module 4Module 4
Module 4
Mitali Chugh
 
Module 5 and 6
Module 5 and 6Module 5 and 6
Module 5 and 6
Mitali Chugh
 
Types of computer
Types of computerTypes of computer
Types of computer
Mitali Chugh
 
Module 2 os
Module 2 osModule 2 os
Module 2 os
Mitali Chugh
 
Os ppt
Os pptOs ppt
Os ppt
Mitali Chugh
 
Upes ppt template
Upes ppt templateUpes ppt template
Upes ppt template
Mitali Chugh
 
Functions
FunctionsFunctions
Functions
Mitali Chugh
 
Structures
StructuresStructures
Structures
Mitali Chugh
 
Functions
FunctionsFunctions
Functions
Mitali Chugh
 
Arrays
ArraysArrays
Arrays
Mitali Chugh
 
Control flow stataements
Control flow stataementsControl flow stataements
Control flow stataements
Mitali Chugh
 
Unit 2 l1
Unit 2 l1Unit 2 l1
Unit 2 l1
Mitali Chugh
 
Unit1
Unit1Unit1
Unit1
Mitali Chugh
 
How to compile and run a c program on ubuntu linux
How to compile and run a c program on ubuntu linuxHow to compile and run a c program on ubuntu linux
How to compile and run a c program on ubuntu linux
Mitali Chugh
 
Blogs
BlogsBlogs
Blogs
Mitali Chugh
 
Module 4
Module 4Module 4
Module 4
Mitali Chugh
 
Ad

Recently uploaded (20)

Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 

Strings

  • 1. Strings A string is a sequence of characters treated as a group. Any group of characters defined between double quotation marks is a string constant. We have already used some string literals: “filename” “output string” Character strings are often used to build meaningful and readable programs. Strings are important in many programming contexts: names other objects (numbers, identifiers, etc.) Operations on strings include: Reading and writing strings, combining strings together, copying one string to another, comparing strings for equality, extracting a portion of a string.
  • 2. Outline Strings Representation in C String Literals String Variables String Input/Output printf, scanf, gets, fgets, puts, fputs String Functions strlen, strcpy, strncpy, strcmp, strncmp, strcat, strncat, strchr, strrchr, strstr, strspn, strcspn, strtok Reading from/Printing to Strings sprintf, sscanf
  • 3. Strings in C No explicit type, instead strings are maintained as arrays of characters Representing strings in C  stored in arrays of characters  array can be of any length  end of string is indicated by a delimiter, the zero character ‘0’ "AString" A 0gnirtS
  • 4. String Literals String literal values are represented by sequences of characters between double quotes (“) Examples “” - empty string “hello” “a” versus ‘a’ ‘a’ is a single character value (stored in 1 byte) as the ASCII value for a “a” is an array with two characters, the first is a, the second is the character value 0
  • 5. Duplicate String Literals Each string literal in a C program is stored at a different location So even if the string literals contain the same string, they are not equal (in the == sense) Example: char string1[6] = “hello”; char string2[6] = “hello”; but string1 does not equal string2 (they are stored at different locations)
  • 6. Declaring and Initializing String Variables Allocate an array of a size large enough to hold the string (plus 1 extra value for the delimiter) Char string_name[size]; Example: char city[10]; Examples (with initialization): char str1[6] = “Hello”; char str2[] = “Hello”; char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’0’}; Note, each variable is considered a constant in that the space it is connected to cannot be changed str1 = str2; /* not allowable, but we can copy the contents of str2 to str1 (more later) */ • When the compiler assigns a character string to a character array it automatically supplies a NULL (o) character at the end of the string.
  • 7. We can declare the size much larger than the string size in the initializer. That is the statement: char str [10]=“GOOD”; is permitted. However the following declaration is illegal. Char str2[3]=“Good”; This will result in compile time error. We cannot separate the initialization from declaration. i.e. char str3[5]; str3=“Good”; Similarly, char s1[4]=“abc”; cahr s2[4]; s2=s1; is not allowed. An array name cannot be used as the left operand of the assignment operator.
  • 8. “Why do we need a terminating NULL character?” A string is not a datatype in C but it is considered a data structure stored in an array. The string is a variable length structure and is stored in a fixed length array. The array size is not always the size of the string and most often it is much larger than the string stored in it. Therefore, the last element of the array need not represent the end of the string. We need some way to determine the end of the string data and the NULL character serves as the “end of string”.
  • 9. Changing String Variables Can change parts of a string variable char str1[6] = “hello”; str1[0] = ‘y’; /* str1 is now “yello” */ str1[4] = ‘0’; /* str1 is now “yell” */ Important to retain delimiter (replacing str1[5] in the original string with something other than ‘0’ makes a string that does not end) Have to stay within limits of array
  • 10. Reading Strings from terminal Use %s field specification in scanf to read string: ignores leading white space reads characters until next white space encountered C stores null (0) char after last non-white space character. Example: char Name[11]; scanf(“%s”,Name); ‘&’ is not required before the variable name. The unused locations are filled with garbage. We can also specify the field width using the form %ws in the scanf statement for reading a specified number of characters from the input string. Ex: scanf(“%ws”, name);
  • 11. Reading Strings from terminal(cont) Can use the width value in the field specification to limit the number of characters read: char Name[11]; scanf(“%10s”,Name); Remember, you need one space for the 0 width should be one less than size of array Strings shorter than the field specification are read normally, but C always stops after reading 10 characters
  • 12. Reading Strings from terminal(cont) %s and %ws can read strings without white spaces i.e. they cannot be used for reading a text containing more than one word. However we can use the following code to read a line: char line[80]; scanf(“[^n]”, line); printf(“%s”, line);
  • 13. String Output Use %s field specification in printf: characters in string printed until 0 encountered char Name[10] = “Rich”; printf(“|%s|”,Name); /* outputs |Rich| */ Can use width value to print string in space: printf(“|%10s|”,Name); /* outputs | Rich| */ Use - flag to left justify: printf(“|%-10s|”,Name); /* outputs |Rich | */
  • 14. Arithmetic operations on characters Whenever a character constant or character variable is used in an expression, it is automatically converted into an integer value by the system. Example: x=‘a’; printf(“%dn”,x); will display 97 on screen which is ASCII value of ‘a’ in lower case. Ex-2 x=‘z’-1 will assign value 121 to variable x. Ex-3 ch>=‘A’ && ch<=‘Z’ would test whether the character contained in variable ch is an upper case letter. C has a function “atoi” that converts a string of digits into their integer values. It is stored in <stdlib.h> Ex: number=“1988”; year=atoi(number);
  • 15. Putting strings together The process of combining two strings together is called concatenation. String3=string1+string2; is not valid. We can combine the strings using the following program:
  • 16. include <stdio.h> int main() { char s1[100], s2[100], i, j; printf("Enter first string: "); scanf("%s", s1); printf("Enter second string: "); scanf("%s", s2); // calculate the length of string s1 // and store it in i for(i = 0; s1[i] != '0'; ++i); for(j = 0; s2[j] != '0'; ++j, ++i) { s1[i] = s2[j]; } s1[i] = '0'; printf("After concatenation: %s", s1); return 0; }
  • 17. String Copy: #include <stdio.h> int main() { char s1[100], s2[100], i; printf("Enter string s1: "); scanf("%s",s1); for(i = 0; s1[i] != '0'; ++i) { s2[i] = s1[i]; } s2[i] = '0'; printf("String s2: %s", s2); return 0; }
  • 18. ASSIGNMENT WAP to compare two strings without using string manipulation functions.
  • 19. The most common functions used from the library are: 1. strlen("name of string") 2. strcpy( dest, source) 3. strcmp( string1, string2 ) 4. strstr( str1, str2 )
  • 20. Declaration and usage of strlen() function It is one of the most useful functions used from this library, whenever we need the length of the string say "str1" we write it as int len; len = strlen(str1); len will be the length of the string "str1".(it will include all the spaces and characters in the string except the NULL('0') character. strlen( string )
  • 21. strcpy() function strcpy( dest, source) This function copies the string "source" to string "dest". Declaration strcpy( str2, str1 );
  • 22. strcmp( str1, str2 ) This function is used to compare two strings "str1" and "str2". this function returns zero("0") if the two compared strings are equal, else some none zero integer. Declaration and usage of strcmp() function strcmp( str1 , str2 ); //declaration if( strcmp( str1, str2 )==0) { printf("string %s and string %s are equaln",str1,str2); } else printf("string %s and string %s are not equaln",str1,str2); Return value - if Return value if < 0 then it indicates str1 is less than str2 - if Return value if > 0 then it indicates str2 is less than str1 - if Return value if = 0 then it indicates str1 is equal to str2
  • 23. strstr(str1, str2) This library function finds the first occurrence of the substring str2 in the string str1. The terminating '0' character is not compared. Declaration strstr( str1, str2); - str1: the main string to be scanned. - str2: the small string to be searched in str1. // let say str2="speed"; //function can also be written as strstr(str1, "speed" ); This function is very useful in checking whether str2 is a substring of str1 or not. Return value This function returns a pointer to the first occurrence in str1 of any of the entire sequence of characters specified in str2, or a NULL pointer if the sequence is not present in str1.
  • 24. Strcat() Used for string concatenation(joining) It takes two arguments i.e. 2 strings Syntax: strcat(string1,string2); After concatenation the resultant string is stored in first string. Exercise: WAP to input two strings, concatenate it and print the resultant string.