SlideShare a Scribd company logo
CProgramming Language
&
Data Structure
Prepared by: Mo’meN M. Ali
E-mail: momen.1993@live.com
References
• www.stackoverflow.com
• C Primer Plus 6th Edition
• Let Us C 5th Edition
• The C Programming Language 2nd Edition
• C Modern Approach 2nd Edition
• Data Structures and Algorithm Analysis in C 2nd Edition
C Programming Language
Mo’meN M. Ali
Review Programs are uploaded to this Git repo
https://github.com/Mo2meN-
Ali/x86/tree/master/Programming%20Course/2-Strings
C Programming Language
Mo’meN M. Ali
Topics
• Arrays & Pointers.
• Character String & String Functions.
• Storage Classes, Linkage & Memory Management.
• File Input/Output.
• Structures & Other Data Formats.
• Bit Fiddling.
• The C Preprocessor & The C Library.
• Algorithm Analysis & ADT.
• Stacks & Queues.
• Trees.
C Programming Language
Mo’meN M. Ali
Today You Will Learn About:
• Functions:
gets(), gets_s(), fgets(), puts(), fputs(), strcat(), strncat(), strcmp(),
strncmp(), strcpy(), strncpy(), sprintf(), strchr().
• Creating and using strings.
• Using several string and character functions from the C library and
creating your own string functions.
• Using command-line arguments.
C Programming Language
Mo’meN M. Ali
C Programming Language
Mo’meN M. Ali
// strings1.c
#include <stdio.h>
#define MSG "I am a symbolic string constant."
#define MAXLENGTH 81
int main(void)
{
char words[MAXLENGTH] = "I am a string in an array.";
const char * pt1 = "Something is pointing at me.";
puts("Here are some strings:");
puts(MSG);
puts(words);
puts(pt1);
words[8] = 'p';
puts(words);
return 0;
}
Output
Here are some strings:
I am an old-fashioned symbolic string constant.
I am a string in an array.
Something is pointing at me.
I am a spring in an array.
C Programming Language
Mo’meN M. Ali
• The puts() function, like printf(), belongs to the stdio.h family of input/output
functions.
• It only displays strings, and, unlike printf(), it automatically appends a newline to
the string it displays.
Note:
Character string constants (string literals)
• A string constant, also termed a string literal, is anything enclosed in double
quotation marks.
• The enclosed characters, plus a terminating 0 character automatically provided
by the compiler, are stored in memory as a character string.
• The principal ways are using string constants, using char arrays, and using char
pointers. A program should make sure there is a place to store a string.
• Character string constants are placed in the static storage class, which means
that if you use a string constant in a function, the string is stored just once and
lasts for the duration of the program, even if the function is called several times.
The entire quoted phrase acts as a pointer to where the string is stored. This
action is analogous to the name of an array acting as a pointer to the array’s
location.
C Programming Language
Mo’meN M. Ali
String Examples
• char greeting[50] = "Hello, and" " how are" " you" " today!";
is equivalent to this:
char greeting[50] = "Hello, and how are you today!";
• printf(""Run, Spot, run!" exclaimed Dick.n");
This produces the following output:
"Run, Spot, run!" exclaimed Dick.
C Programming Language
Mo’meN M. Ali
C Programming Language
Mo’meN M. Ali
/* strptr.c -- strings as pointers */
#include <stdio.h>
int main(void)
{
printf("%s, %p, %cn", "We", "are", *"space farers");
return 0;
}
1. The %s format should print the string We.
2. The %p format produces an address. So if the phrase "are" is an address,
then %p should print the address of the first character in the string. (Pre-ANSI
implementations might have to use %u or %lu instead of %p).
3. *"space farers" should produce the value to which the address points,
which should be the first character of the string "space farers“.
Output
We, 0x100000f61, s
C Programming Language
Mo’meN M. Ali
Array and pointer differences
• What’s The differences between initializing a character array to hold a string and
initializing a pointer to point to a string. (By "pointing to a string," we really mean pointing
to the first character of a string.) ?
char heart[] = "I love Tillie!";
char *head = "I love Millie!";
• The chief difference is that the array name heart is a constant, but the pointer head is a
variable. What practical difference does this make?
C Programming Language
Mo’meN M. Ali
C Programming Language
Mo’meN M. Ali
#define MSG "I'm special."
#include <stdio.h>
int main(void)
{
char ar[] = MSG;
const char *pt = MSG;
printf("address of "I'm special": %p n", "I'm special");
printf(" address ar: %pn", ar);
printf(" address pt: %pn", pt);
printf(" address of MSG: %pn", MSG);
printf("address of "I'm special": %p n", "I'm special");
return 0;
}
Output
address of "I'm special": 0x100000f0c
address ar: 0x7fff5fbff8c7
address pt: 0x100000ee0
address of MSG: 0x100000ee0
address of "I'm special": 0x100000f0c
C Programming Language
Mo’meN M. Ali
Arrays of character strings
const char *mytal[LIM] = {
"Adding numbers swiftly",
"Multiplying accurately", "Stashing data",
"Following instructions to the letter",
"Understanding the C language“
};
• Because LIM is 5, you can say that mytal is an array of five pointers-to-char. That is,
mytal is a one-dimensional array, and each element in the array holds the address of a
char. The first pointer is mytal[0], and it points to the first character of the first string.
The second pointer is mytal[1], and it points to the beginning of the second string. In
general, each pointer points to the first character of the corresponding string
• Review Program: Array as Pointers
C Programming Language
Mo’meN M. Ali
Rectangular versus ragged array
C Programming Language
Mo’meN M. Ali
The unfortunate gets() function
• It’s a simple function, easy to use:
1. It reads an entire line up through the newline character.
2. Discards the newline character, stores the remaining characters.
3. Adding a null character to create a C string.
• The problem is that gets() doesn’t check to see if the input line actually fits into
the array, also, remember C naturally does not check for boundaries!!
C Programming Language
Mo’meN M. Ali
C Programming Language
Mo’meN M. Ali
/* getsputs.c -- using gets() and puts() */
#include <stdio.h>
#define STLEN 81
int main(void)
{
char words[STLEN];
puts("Enter a string, please.");
gets(words);
printf("Your string twice:n");
printf("%sn", words);
puts(words);
puts("Done.");
return 0;
}
Output
Enter a string, please.
I want to learn about string theory!
Your string twice:
I want to learn about string theory!
I want to learn about string theory!
Done.
C Programming Language
Mo’meN M. Ali
puts() function
• It take a string argument then prints it with adding a new line.
• Which make it a natural company for the gets() function which discards the new
line from input string.
C Programming Language
Mo’meN M. Ali
The fgets() function (and fputs() )
• The fgets() function meets the possible overflow problem by taking a second
argument that limits the number of characters to be read. This function is
designed for file input, which makes it a little more awkward to use. Here is how
fgets() differs from gets() :
1. It takes a second argument indicating the maximum number of characters
to read. If this argument has the value n , fgets() reads up to n-1 characters
or through the newline character, whichever comes first.
2. If fgets() reads the newline, it stores it in the string, unlike gets(), which
discards it.
3. It takes a third argument indicating which file to read. To read from the
keyboard, use stdin (for standard input ) as the argument; this identifier is
defined in stdio.h.
C Programming Language
Mo’meN M. Ali
fputs() function
• It take a string argument then prints it without adding a new line.
• Which make it a natural company for the fgets() function which discards the new
line from input string.
C Programming Language
Mo’meN M. Ali
C Programming Language
Mo’meN M. Ali
#include <stdio.h>
#define STLEN 14
int main(void)
{
char words[STLEN];
puts("Enter a string, please.");
fgets(words, STLEN, stdin);
printf("Your string twice (puts(), then fputs()):n");
puts(words);
fputs(words, stdout);
puts("Enter another string, please.");
fgets(words, STLEN, stdin);
printf("Your string twice (puts(), then fputs()):n");
puts(words);
fputs(words, stdout);
puts("Done.");
return 0;
}
Output
Enter a string, please.
apple pie
Your string twice (puts(), then fputs()):
apple pie
apple pie
Enter another string, please.
strawberry shortcake
Your string twice (puts(), then fputs()):
strawberry sh
strawberry shDone.
Review Program: fgets
C Programming Language
Mo’meN M. Ali
The gets_s() function
• The three main differences from fgets() are these:
1. gets_s() just reads from the standard input, so it doesn’t need a third argument.
2. If gets_s() does read a newline; it discards it rather than storing it.
3. If gets_s() reads the maximum number of characters and fails to read a
newline, it takes several steps. It sets the first character of the
destination array to the null character.It reads and discards subsequent
input until a newline or end-of-file is encountered. It returns the null
pointer. It invokes an implementation-dependent “handler” function (or
else one you’ve selected), which may cause the program to exit or abort.
C Programming Language
Mo’meN M. Ali
The s_gets() function
C Programming Language
Mo’meN M. Ali
char *s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val) // i.e., ret_val != NULL
{
while (st[i] != 'n' && st[i] != '0')
i++;
if (st[i] == 'n')
st[i] = '0';
else // must have words[i] == '0'
while (getchar() != 'n')
continue;
}
return ret_val;
}
The scanf() function
• The chief difference between scanf() and gets() lies in how they decide when they have reached
the end of the string:
scanf() is more of a "get word" than a "get string" function. The gets()
function, as you've seen, takes in all the characters up to the first newline. The scanf()
function has two choices for terminating input. For either choice, the string starts at the
first non-whitespace character encountered. If you use the %s format, the string runs up
to (but not including) the next whitespace character (blank, tab, or newline). If you
specify a field width, as in %10s, the scanf() collects up to 10 characters or up to the first
whitespace character, whichever comes first.
Mo’meN M. Ali
C Programming Language
C Programming Language
Mo’meN M. Ali
/* scan_str.c -- using scanf() */
#include <stdio.h>
int main(void)
{
char name1[11], name2[11];
int count;
printf("Please enter 2 names.n");
count = scanf("%5s %10s",name1, name2);
printf("I read the %d names %s and %s.n",
count, name1, name2);
return 0;
}
Output
Please enter 2 names.
Jesse Jukes
I read the 2 names Jesse and Jukes.
Please enter 2 names.
Liza Applebottham
I read the 2 names Liza and Applebotth.
Please enter 2 names.
Portensia Callowit
I read the 2 names Porte and nsia.
C Programming Language
Mo’meN M. Ali
Exercise 2.0
30 Minutes
MO’MEN M. ALI
C Programming Language
The Do-it-Yourself Option
• Surprisingly enough, C offers a way to build your own string functions the
way you want.
• Using getchar(), putchar() and string.h functions.
C Programming Language
Mo’meN M. Ali
C Programming Language
Mo’meN M. Ali
/* put1.c -- prints a string without adding n */
#include <stdio.h>
void put1(const char *string) /* string not altered */
{
while (*string != '0')
putchar(*string++);
}
• use const char *string rather than const char string[] as the
formal argument? Technically, the two are equivalent, so either form will work.
One reason to use bracket notation is to remind the user that the function
processes an array. With strings, however, the actual argument can be the
name of an array, a quoted string, or a variable that has been declared as type
char *. Using const char *string reminds you that the actual argument
isn’t necessarily an array.
Note
C Programming Language
Mo’meN M. Ali
/* put2.c -- prints a string and counts characters */
#include <stdio.h>
int put2(const char * string)
{
int count = 0;
while (*string) /* common idiom */
{
putchar(*string++);
count++;
}
putchar('n'); /* newline not counted */
return(count);
}
Review Program: Put1_Put2
String library’s functions
• he C library supplies several string-handling functions; ANSI C uses the string.h
header file to provide the prototypes. We'll look at some of the most useful and
common ones: strlen(), strcat(), strncat(), strcmp(), strncmp(), strcpy(), and
strncpy(). We'll also examine sprintf(), supported by the stdio.h header file.
C Programming Language
Mo’meN M. Ali
The strlen() function
The strlen() function, finds the length of a string. it adds 1 to the combined lengths to
allow space for the null character.
/* fit.c –– procrustean function */
void fit(char * string, unsigned int size)
{
if (strlen(string) > size)
*(string + size) = '0';
}
• This function does change the string, so the function header doesn't use const in
declaring the formal parameter string.
• Review Program: TestFit
C Programming Language
Mo’meN M. Ali
The strcat() function
• The strcat() (for string concatenation) function takes two strings for arguments. A
copy of the second string is tacked onto the end of the first, and this combined
version becomes the new first string. The second string is not altered. It returns the
value of its first argument.
• Review Program: StringConcatenation
C Programming Language
Mo’meN M. Ali
The strncat() function
• strncat() differs from strcat() in only one aspect which that, it takes a second
argument indicating the maximum number of characters to add.
• Review Program: StringConcatenation with checking
C Programming Language
Mo’meN M. Ali
The strcmp() function
• The strcmp() function, Compares two string. It returns a negative number if the first
string precedes the second alphabetically and that it returns a positive number if the
order is the other way and it returns zero if the two strings are identical.
C Programming Language
Mo’meN M. Ali
Note:
The strcmp() function is for comparing strings , not characters . So you can use
arguments such as "apples" and "A" , but you cannot use character arguments, such as
'A‘.
• Review Program: String Comparison
The strncmp() function
• The strncmp() function is different from strcmp() in one manner which that it
compares the strings until they differ or until it has compared a number of
characters specified by a third argument.
C Programming Language
Mo’meN M. Ali
The strcpy() function
• The strncpy() function copies the second argument string into the first argument string.
1. The first argument need not point to the beginning of an array; this lets you copy just
part of an array.
2. It returns the value of its first argument.
3. It does no check to see if the first argument has the space or not which may
cause overflow problems.
C Programming Language
Mo’meN M. Ali
The strncpy() function
• The strncpy() function only difference that it copies the n character of the second
argument string into the first argument string.
• Review Program: String Copy
The sprintf() function
• The sprintf() function is declared in stdio.h instead of string.h. It works like printf(),
but it writes to a string instead of writing to a display. Therefore, it provides a way to
combine several elements into a single string. The first argument to sprintf() is the
address of the target string. The remaining arguments are the same as for printf()—
a conversion specification string followed by a list of items to be written
C Programming Language
Mo’meN M. Ali
• Review Program: form a string
Other String Functions
MO’MEN M. ALI
C Programming Language
Search Yourself
Exercise 2.1
30 Minutes
MO’MEN M. ALI
C Programming Language
Selection Sort Algorithm
Sorts a list of a strings alphabetically
C Programming Language
Mo’meN M. Ali
• Review Program: Sorting String
Command-Line Arguments
• The command line is the line you type to run your program in a command-line
environment.
• Command-Line Programs takes input into a special Argument called *argv[]
which is Array of pointers.
• All input to the program are saved as strings in *argv[] one by one.
• argv[0] always contains the name of the program. So user input is to be
found strating from argv[1].
• argc contains the number of inputs that has been passed to the program plus
the program name.
C Programming Language
Mo’meN M. Ali
• Review Program: form a string
C Programming Language
Mo’meN M. Ali
/* repeat.c -- main() with arguments */
#include <stdio.h>
int main(int argc, char *argv[])
{
int count;
printf("The command line has %d arguments:n", argc - 1);
for (count = 1; count < argc; count++)
printf("%d: %sn", count, argv[count]);
printf("n");
return 0;
}
Output
$ repeat Resistance is futile
The command line has 3 arguments:
1: Resistance
2: is
3: futile
C Programming Language
Mo’meN M. Ali
C Programming Language
Mo’meN M. Ali
/* hello.c -- converts command-line argument to number */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i, times;
if (argc < 2 || (times = atoi(argv[1])) < 1)
printf("Usage: %s positive-numbern", argv[0]);
else
for (i = 0; i < times; i++)
puts("Hello, good looking!");
return 0;
}
Output
$ hello 3
Hello, good looking!
Hello, good looking!
Hello, good looking!
C Programming Language
Mo’meN M. Ali
THANK YOUSEE YOU SOON
C Programming Language
Mo’meN M. Ali

More Related Content

What's hot (19)

C programming session 05
C programming session 05C programming session 05
C programming session 05
Dushmanta Nath
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
arshpreetkaur07
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
Sudheer Kiran
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
M-TEC Computer Education
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
nmahi96
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
Dushmanta Nath
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
Emertxe Information Technologies Pvt Ltd
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
C programming language
C programming languageC programming language
C programming language
Mahmoud Eladawi
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
Dushmanta Nath
 
Structures
StructuresStructures
Structures
arshpreetkaur07
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
Jussi Pohjolainen
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
Srikanth
 
Data types in c++
Data types in c++ Data types in c++
Data types in c++
RushikeshGaikwad28
 
C interview-questions-techpreparation
C interview-questions-techpreparationC interview-questions-techpreparation
C interview-questions-techpreparation
Kushaal Singla
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
Dushmanta Nath
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
arshpreetkaur07
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
Sudheer Kiran
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
nmahi96
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
Dushmanta Nath
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
Dushmanta Nath
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
Srikanth
 
C interview-questions-techpreparation
C interview-questions-techpreparationC interview-questions-techpreparation
C interview-questions-techpreparation
Kushaal Singla
 

Viewers also liked (20)

String operation
String operationString operation
String operation
Shakila Mahjabin
 
Economics Perfect Market Competition
Economics Perfect Market CompetitionEconomics Perfect Market Competition
Economics Perfect Market Competition
Anshuman Singh
 
String & its application
String & its applicationString & its application
String & its application
Tech_MX
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
gourav kottawar
 
C programming & data structure
C programming & data structureC programming & data structure
C programming & data structure
rajeev_123
 
C mcq practice test 2
C mcq practice test 2C mcq practice test 2
C mcq practice test 2
Aman Kamboj
 
Software Engineering for Web Applications
Software Engineering for Web ApplicationsSoftware Engineering for Web Applications
Software Engineering for Web Applications
Moh'd Shakeb Baig
 
Array in Java
Array in JavaArray in Java
Array in Java
Ali shah
 
Introduction into Social Network Analysis
Introduction into Social Network AnalysisIntroduction into Social Network Analysis
Introduction into Social Network Analysis
Dragan Gasevic
 
C mcq practice test 1
C mcq practice test 1C mcq practice test 1
C mcq practice test 1
Aman Kamboj
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
Fahim Adil
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
Ashim Lamichhane
 
Open and closed thermodynamic system
Open and closed thermodynamic systemOpen and closed thermodynamic system
Open and closed thermodynamic system
physics101
 
String functions in C
String functions in CString functions in C
String functions in C
baabtra.com - No. 1 supplier of quality freshers
 
Design And Implementation Of A Bangla Compiler
Design And Implementation Of A Bangla CompilerDesign And Implementation Of A Bangla Compiler
Design And Implementation Of A Bangla Compiler
MJ Ferdous
 
System software and operating system
System software and operating systemSystem software and operating system
System software and operating system
dhruv bhandari
 
Crytography
CrytographyCrytography
Crytography
Subesh Kumar Yadav
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
Ravi_Kant_Sahu
 
Gcse Forces And Motion
Gcse Forces And MotionGcse Forces And Motion
Gcse Forces And Motion
Tauseef Khan
 
Cryptography
CryptographyCryptography
Cryptography
Kural Amudhan
 
Economics Perfect Market Competition
Economics Perfect Market CompetitionEconomics Perfect Market Competition
Economics Perfect Market Competition
Anshuman Singh
 
String & its application
String & its applicationString & its application
String & its application
Tech_MX
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
gourav kottawar
 
C programming & data structure
C programming & data structureC programming & data structure
C programming & data structure
rajeev_123
 
C mcq practice test 2
C mcq practice test 2C mcq practice test 2
C mcq practice test 2
Aman Kamboj
 
Software Engineering for Web Applications
Software Engineering for Web ApplicationsSoftware Engineering for Web Applications
Software Engineering for Web Applications
Moh'd Shakeb Baig
 
Array in Java
Array in JavaArray in Java
Array in Java
Ali shah
 
Introduction into Social Network Analysis
Introduction into Social Network AnalysisIntroduction into Social Network Analysis
Introduction into Social Network Analysis
Dragan Gasevic
 
C mcq practice test 1
C mcq practice test 1C mcq practice test 1
C mcq practice test 1
Aman Kamboj
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
Fahim Adil
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
Ashim Lamichhane
 
Open and closed thermodynamic system
Open and closed thermodynamic systemOpen and closed thermodynamic system
Open and closed thermodynamic system
physics101
 
Design And Implementation Of A Bangla Compiler
Design And Implementation Of A Bangla CompilerDesign And Implementation Of A Bangla Compiler
Design And Implementation Of A Bangla Compiler
MJ Ferdous
 
System software and operating system
System software and operating systemSystem software and operating system
System software and operating system
dhruv bhandari
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
Ravi_Kant_Sahu
 
Gcse Forces And Motion
Gcse Forces And MotionGcse Forces And Motion
Gcse Forces And Motion
Tauseef Khan
 
Ad

Similar to C programming & data structure [character strings & string functions] (20)

9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
MomenMostafa
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPTCfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
ChapterabcdefghijklmnopqrdstuvwxydanniipoChapterabcdefghijklmnopqrdstuvwxydanniipo
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
[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
 
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
 
string function with example...................
string function with example...................string function with example...................
string function with example...................
NishantsrivastavaV
 
pps unit 3.pptx
pps unit 3.pptxpps unit 3.pptx
pps unit 3.pptx
mathesh0303
 
String notes
String notesString notes
String notes
Prasadu Peddi
 
string.ppt
string.pptstring.ppt
string.ppt
lakshmanarao027MVGRC
 
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 IN C
Strings IN CStrings IN C
Strings IN C
yndaravind
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
OluwafolakeOjo
 
String.pptx
String.pptxString.pptx
String.pptx
Ananthi Palanisamy
 
Strings
StringsStrings
Strings
Mitali Chugh
 
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
 
C Programming Strings.docx
C Programming Strings.docxC Programming Strings.docx
C Programming Strings.docx
8759000398
 
CSE 1102 - Lecture_7 - Strings_in_C.pptx
CSE 1102 - Lecture_7 - Strings_in_C.pptxCSE 1102 - Lecture_7 - Strings_in_C.pptx
CSE 1102 - Lecture_7 - Strings_in_C.pptx
Salim Shadman Ankur
 
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
Sowri Rajan
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
MomenMostafa
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPTCfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
ChapterabcdefghijklmnopqrdstuvwxydanniipoChapterabcdefghijklmnopqrdstuvwxydanniipo
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
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
 
string function with example...................
string function with example...................string function with example...................
string function with example...................
NishantsrivastavaV
 
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
 
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
 
C Programming Strings.docx
C Programming Strings.docxC Programming Strings.docx
C Programming Strings.docx
8759000398
 
CSE 1102 - Lecture_7 - Strings_in_C.pptx
CSE 1102 - Lecture_7 - Strings_in_C.pptxCSE 1102 - Lecture_7 - Strings_in_C.pptx
CSE 1102 - Lecture_7 - Strings_in_C.pptx
Salim Shadman Ankur
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
Sowri Rajan
 
Ad

More from MomenMostafa (9)

8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointers
MomenMostafa
 
7 functions
7  functions7  functions
7 functions
MomenMostafa
 
6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping
MomenMostafa
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements looping
MomenMostafa
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
MomenMostafa
 
2 data and c
2 data and c2 data and c
2 data and c
MomenMostafa
 
1 introducing c language
1  introducing c language1  introducing c language
1 introducing c language
MomenMostafa
 
3 character strings and formatted input output
3  character strings and formatted input output3  character strings and formatted input output
3 character strings and formatted input output
MomenMostafa
 
Embedded System Practical Workshop using the ARM Processor
Embedded System Practical Workshop using the ARM ProcessorEmbedded System Practical Workshop using the ARM Processor
Embedded System Practical Workshop using the ARM Processor
MomenMostafa
 
8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointers
MomenMostafa
 
6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping
MomenMostafa
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements looping
MomenMostafa
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
MomenMostafa
 
1 introducing c language
1  introducing c language1  introducing c language
1 introducing c language
MomenMostafa
 
3 character strings and formatted input output
3  character strings and formatted input output3  character strings and formatted input output
3 character strings and formatted input output
MomenMostafa
 
Embedded System Practical Workshop using the ARM Processor
Embedded System Practical Workshop using the ARM ProcessorEmbedded System Practical Workshop using the ARM Processor
Embedded System Practical Workshop using the ARM Processor
MomenMostafa
 

Recently uploaded (20)

Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 

C programming & data structure [character strings & string functions]

  • 2. References • www.stackoverflow.com • C Primer Plus 6th Edition • Let Us C 5th Edition • The C Programming Language 2nd Edition • C Modern Approach 2nd Edition • Data Structures and Algorithm Analysis in C 2nd Edition C Programming Language Mo’meN M. Ali
  • 3. Review Programs are uploaded to this Git repo https://github.com/Mo2meN- Ali/x86/tree/master/Programming%20Course/2-Strings C Programming Language Mo’meN M. Ali
  • 4. Topics • Arrays & Pointers. • Character String & String Functions. • Storage Classes, Linkage & Memory Management. • File Input/Output. • Structures & Other Data Formats. • Bit Fiddling. • The C Preprocessor & The C Library. • Algorithm Analysis & ADT. • Stacks & Queues. • Trees. C Programming Language Mo’meN M. Ali
  • 5. Today You Will Learn About: • Functions: gets(), gets_s(), fgets(), puts(), fputs(), strcat(), strncat(), strcmp(), strncmp(), strcpy(), strncpy(), sprintf(), strchr(). • Creating and using strings. • Using several string and character functions from the C library and creating your own string functions. • Using command-line arguments. C Programming Language Mo’meN M. Ali
  • 6. C Programming Language Mo’meN M. Ali // strings1.c #include <stdio.h> #define MSG "I am a symbolic string constant." #define MAXLENGTH 81 int main(void) { char words[MAXLENGTH] = "I am a string in an array."; const char * pt1 = "Something is pointing at me."; puts("Here are some strings:"); puts(MSG); puts(words); puts(pt1); words[8] = 'p'; puts(words); return 0; }
  • 7. Output Here are some strings: I am an old-fashioned symbolic string constant. I am a string in an array. Something is pointing at me. I am a spring in an array. C Programming Language Mo’meN M. Ali • The puts() function, like printf(), belongs to the stdio.h family of input/output functions. • It only displays strings, and, unlike printf(), it automatically appends a newline to the string it displays. Note:
  • 8. Character string constants (string literals) • A string constant, also termed a string literal, is anything enclosed in double quotation marks. • The enclosed characters, plus a terminating 0 character automatically provided by the compiler, are stored in memory as a character string. • The principal ways are using string constants, using char arrays, and using char pointers. A program should make sure there is a place to store a string. • Character string constants are placed in the static storage class, which means that if you use a string constant in a function, the string is stored just once and lasts for the duration of the program, even if the function is called several times. The entire quoted phrase acts as a pointer to where the string is stored. This action is analogous to the name of an array acting as a pointer to the array’s location. C Programming Language Mo’meN M. Ali
  • 9. String Examples • char greeting[50] = "Hello, and" " how are" " you" " today!"; is equivalent to this: char greeting[50] = "Hello, and how are you today!"; • printf(""Run, Spot, run!" exclaimed Dick.n"); This produces the following output: "Run, Spot, run!" exclaimed Dick. C Programming Language Mo’meN M. Ali
  • 10. C Programming Language Mo’meN M. Ali /* strptr.c -- strings as pointers */ #include <stdio.h> int main(void) { printf("%s, %p, %cn", "We", "are", *"space farers"); return 0; } 1. The %s format should print the string We. 2. The %p format produces an address. So if the phrase "are" is an address, then %p should print the address of the first character in the string. (Pre-ANSI implementations might have to use %u or %lu instead of %p). 3. *"space farers" should produce the value to which the address points, which should be the first character of the string "space farers“.
  • 11. Output We, 0x100000f61, s C Programming Language Mo’meN M. Ali
  • 12. Array and pointer differences • What’s The differences between initializing a character array to hold a string and initializing a pointer to point to a string. (By "pointing to a string," we really mean pointing to the first character of a string.) ? char heart[] = "I love Tillie!"; char *head = "I love Millie!"; • The chief difference is that the array name heart is a constant, but the pointer head is a variable. What practical difference does this make? C Programming Language Mo’meN M. Ali
  • 13. C Programming Language Mo’meN M. Ali #define MSG "I'm special." #include <stdio.h> int main(void) { char ar[] = MSG; const char *pt = MSG; printf("address of "I'm special": %p n", "I'm special"); printf(" address ar: %pn", ar); printf(" address pt: %pn", pt); printf(" address of MSG: %pn", MSG); printf("address of "I'm special": %p n", "I'm special"); return 0; }
  • 14. Output address of "I'm special": 0x100000f0c address ar: 0x7fff5fbff8c7 address pt: 0x100000ee0 address of MSG: 0x100000ee0 address of "I'm special": 0x100000f0c C Programming Language Mo’meN M. Ali
  • 15. Arrays of character strings const char *mytal[LIM] = { "Adding numbers swiftly", "Multiplying accurately", "Stashing data", "Following instructions to the letter", "Understanding the C language“ }; • Because LIM is 5, you can say that mytal is an array of five pointers-to-char. That is, mytal is a one-dimensional array, and each element in the array holds the address of a char. The first pointer is mytal[0], and it points to the first character of the first string. The second pointer is mytal[1], and it points to the beginning of the second string. In general, each pointer points to the first character of the corresponding string • Review Program: Array as Pointers C Programming Language Mo’meN M. Ali
  • 16. Rectangular versus ragged array C Programming Language Mo’meN M. Ali
  • 17. The unfortunate gets() function • It’s a simple function, easy to use: 1. It reads an entire line up through the newline character. 2. Discards the newline character, stores the remaining characters. 3. Adding a null character to create a C string. • The problem is that gets() doesn’t check to see if the input line actually fits into the array, also, remember C naturally does not check for boundaries!! C Programming Language Mo’meN M. Ali
  • 18. C Programming Language Mo’meN M. Ali /* getsputs.c -- using gets() and puts() */ #include <stdio.h> #define STLEN 81 int main(void) { char words[STLEN]; puts("Enter a string, please."); gets(words); printf("Your string twice:n"); printf("%sn", words); puts(words); puts("Done."); return 0; }
  • 19. Output Enter a string, please. I want to learn about string theory! Your string twice: I want to learn about string theory! I want to learn about string theory! Done. C Programming Language Mo’meN M. Ali
  • 20. puts() function • It take a string argument then prints it with adding a new line. • Which make it a natural company for the gets() function which discards the new line from input string. C Programming Language Mo’meN M. Ali
  • 21. The fgets() function (and fputs() ) • The fgets() function meets the possible overflow problem by taking a second argument that limits the number of characters to be read. This function is designed for file input, which makes it a little more awkward to use. Here is how fgets() differs from gets() : 1. It takes a second argument indicating the maximum number of characters to read. If this argument has the value n , fgets() reads up to n-1 characters or through the newline character, whichever comes first. 2. If fgets() reads the newline, it stores it in the string, unlike gets(), which discards it. 3. It takes a third argument indicating which file to read. To read from the keyboard, use stdin (for standard input ) as the argument; this identifier is defined in stdio.h. C Programming Language Mo’meN M. Ali
  • 22. fputs() function • It take a string argument then prints it without adding a new line. • Which make it a natural company for the fgets() function which discards the new line from input string. C Programming Language Mo’meN M. Ali
  • 23. C Programming Language Mo’meN M. Ali #include <stdio.h> #define STLEN 14 int main(void) { char words[STLEN]; puts("Enter a string, please."); fgets(words, STLEN, stdin); printf("Your string twice (puts(), then fputs()):n"); puts(words); fputs(words, stdout); puts("Enter another string, please."); fgets(words, STLEN, stdin); printf("Your string twice (puts(), then fputs()):n"); puts(words); fputs(words, stdout); puts("Done."); return 0; }
  • 24. Output Enter a string, please. apple pie Your string twice (puts(), then fputs()): apple pie apple pie Enter another string, please. strawberry shortcake Your string twice (puts(), then fputs()): strawberry sh strawberry shDone. Review Program: fgets C Programming Language Mo’meN M. Ali
  • 25. The gets_s() function • The three main differences from fgets() are these: 1. gets_s() just reads from the standard input, so it doesn’t need a third argument. 2. If gets_s() does read a newline; it discards it rather than storing it. 3. If gets_s() reads the maximum number of characters and fails to read a newline, it takes several steps. It sets the first character of the destination array to the null character.It reads and discards subsequent input until a newline or end-of-file is encountered. It returns the null pointer. It invokes an implementation-dependent “handler” function (or else one you’ve selected), which may cause the program to exit or abort. C Programming Language Mo’meN M. Ali
  • 26. The s_gets() function C Programming Language Mo’meN M. Ali char *s_gets(char * st, int n) { char * ret_val; int i = 0; ret_val = fgets(st, n, stdin); if (ret_val) // i.e., ret_val != NULL { while (st[i] != 'n' && st[i] != '0') i++; if (st[i] == 'n') st[i] = '0'; else // must have words[i] == '0' while (getchar() != 'n') continue; } return ret_val; }
  • 27. The scanf() function • The chief difference between scanf() and gets() lies in how they decide when they have reached the end of the string: scanf() is more of a "get word" than a "get string" function. The gets() function, as you've seen, takes in all the characters up to the first newline. The scanf() function has two choices for terminating input. For either choice, the string starts at the first non-whitespace character encountered. If you use the %s format, the string runs up to (but not including) the next whitespace character (blank, tab, or newline). If you specify a field width, as in %10s, the scanf() collects up to 10 characters or up to the first whitespace character, whichever comes first. Mo’meN M. Ali C Programming Language
  • 28. C Programming Language Mo’meN M. Ali /* scan_str.c -- using scanf() */ #include <stdio.h> int main(void) { char name1[11], name2[11]; int count; printf("Please enter 2 names.n"); count = scanf("%5s %10s",name1, name2); printf("I read the %d names %s and %s.n", count, name1, name2); return 0; }
  • 29. Output Please enter 2 names. Jesse Jukes I read the 2 names Jesse and Jukes. Please enter 2 names. Liza Applebottham I read the 2 names Liza and Applebotth. Please enter 2 names. Portensia Callowit I read the 2 names Porte and nsia. C Programming Language Mo’meN M. Ali
  • 30. Exercise 2.0 30 Minutes MO’MEN M. ALI C Programming Language
  • 31. The Do-it-Yourself Option • Surprisingly enough, C offers a way to build your own string functions the way you want. • Using getchar(), putchar() and string.h functions. C Programming Language Mo’meN M. Ali
  • 32. C Programming Language Mo’meN M. Ali /* put1.c -- prints a string without adding n */ #include <stdio.h> void put1(const char *string) /* string not altered */ { while (*string != '0') putchar(*string++); } • use const char *string rather than const char string[] as the formal argument? Technically, the two are equivalent, so either form will work. One reason to use bracket notation is to remind the user that the function processes an array. With strings, however, the actual argument can be the name of an array, a quoted string, or a variable that has been declared as type char *. Using const char *string reminds you that the actual argument isn’t necessarily an array. Note
  • 33. C Programming Language Mo’meN M. Ali /* put2.c -- prints a string and counts characters */ #include <stdio.h> int put2(const char * string) { int count = 0; while (*string) /* common idiom */ { putchar(*string++); count++; } putchar('n'); /* newline not counted */ return(count); } Review Program: Put1_Put2
  • 34. String library’s functions • he C library supplies several string-handling functions; ANSI C uses the string.h header file to provide the prototypes. We'll look at some of the most useful and common ones: strlen(), strcat(), strncat(), strcmp(), strncmp(), strcpy(), and strncpy(). We'll also examine sprintf(), supported by the stdio.h header file. C Programming Language Mo’meN M. Ali
  • 35. The strlen() function The strlen() function, finds the length of a string. it adds 1 to the combined lengths to allow space for the null character. /* fit.c –– procrustean function */ void fit(char * string, unsigned int size) { if (strlen(string) > size) *(string + size) = '0'; } • This function does change the string, so the function header doesn't use const in declaring the formal parameter string. • Review Program: TestFit C Programming Language Mo’meN M. Ali
  • 36. The strcat() function • The strcat() (for string concatenation) function takes two strings for arguments. A copy of the second string is tacked onto the end of the first, and this combined version becomes the new first string. The second string is not altered. It returns the value of its first argument. • Review Program: StringConcatenation C Programming Language Mo’meN M. Ali
  • 37. The strncat() function • strncat() differs from strcat() in only one aspect which that, it takes a second argument indicating the maximum number of characters to add. • Review Program: StringConcatenation with checking C Programming Language Mo’meN M. Ali
  • 38. The strcmp() function • The strcmp() function, Compares two string. It returns a negative number if the first string precedes the second alphabetically and that it returns a positive number if the order is the other way and it returns zero if the two strings are identical. C Programming Language Mo’meN M. Ali Note: The strcmp() function is for comparing strings , not characters . So you can use arguments such as "apples" and "A" , but you cannot use character arguments, such as 'A‘. • Review Program: String Comparison
  • 39. The strncmp() function • The strncmp() function is different from strcmp() in one manner which that it compares the strings until they differ or until it has compared a number of characters specified by a third argument. C Programming Language Mo’meN M. Ali
  • 40. The strcpy() function • The strncpy() function copies the second argument string into the first argument string. 1. The first argument need not point to the beginning of an array; this lets you copy just part of an array. 2. It returns the value of its first argument. 3. It does no check to see if the first argument has the space or not which may cause overflow problems. C Programming Language Mo’meN M. Ali The strncpy() function • The strncpy() function only difference that it copies the n character of the second argument string into the first argument string. • Review Program: String Copy
  • 41. The sprintf() function • The sprintf() function is declared in stdio.h instead of string.h. It works like printf(), but it writes to a string instead of writing to a display. Therefore, it provides a way to combine several elements into a single string. The first argument to sprintf() is the address of the target string. The remaining arguments are the same as for printf()— a conversion specification string followed by a list of items to be written C Programming Language Mo’meN M. Ali • Review Program: form a string
  • 42. Other String Functions MO’MEN M. ALI C Programming Language Search Yourself
  • 43. Exercise 2.1 30 Minutes MO’MEN M. ALI C Programming Language
  • 44. Selection Sort Algorithm Sorts a list of a strings alphabetically C Programming Language Mo’meN M. Ali • Review Program: Sorting String
  • 45. Command-Line Arguments • The command line is the line you type to run your program in a command-line environment. • Command-Line Programs takes input into a special Argument called *argv[] which is Array of pointers. • All input to the program are saved as strings in *argv[] one by one. • argv[0] always contains the name of the program. So user input is to be found strating from argv[1]. • argc contains the number of inputs that has been passed to the program plus the program name. C Programming Language Mo’meN M. Ali • Review Program: form a string
  • 46. C Programming Language Mo’meN M. Ali /* repeat.c -- main() with arguments */ #include <stdio.h> int main(int argc, char *argv[]) { int count; printf("The command line has %d arguments:n", argc - 1); for (count = 1; count < argc; count++) printf("%d: %sn", count, argv[count]); printf("n"); return 0; }
  • 47. Output $ repeat Resistance is futile The command line has 3 arguments: 1: Resistance 2: is 3: futile C Programming Language Mo’meN M. Ali
  • 48. C Programming Language Mo’meN M. Ali /* hello.c -- converts command-line argument to number */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i, times; if (argc < 2 || (times = atoi(argv[1])) < 1) printf("Usage: %s positive-numbern", argv[0]); else for (i = 0; i < times; i++) puts("Hello, good looking!"); return 0; }
  • 49. Output $ hello 3 Hello, good looking! Hello, good looking! Hello, good looking! C Programming Language Mo’meN M. Ali
  • 50. THANK YOUSEE YOU SOON C Programming Language Mo’meN M. Ali