SlideShare a Scribd company logo
C Programming Language
Mo’meN Ali
Character Strings and String
Functions
#include <stdio.h>
#define MSG "You must have many talents. Tell me some."
// a symbolic string constant
#define LIM 5
#define LINELEN 81 // maximum string length + 1
int main(void)
{
char name[LINELEN];
char talents[LINELEN];
int i;
// initializing a dimensioned char array
const char m1[40] = "Limit yourself to one line's worth.";
// letting the compiler compute the array size
const char m2[] = "If you can't think of anything, fake it.";
const char *m3 = "nEnough about me -- what's your name?"; // initializing a pointer
// initializing an array of string pointers
const char *mytal[LIM] = { // array of 5 pointers
"Adding numbers swiftly",
"Multiplying accurately", "Stashing data",
"Following instructions to the letter",
"Understanding the C language"
};
printf("Hi! I'm Clyde the Computer."
" I have many talents.n");
printf("Let me tell you some of them.n");
puts("What were they? Ah, yes, here's a partial list.");
for (i = 0; i < LIM; i++)
puts(mytal[i]); // print list of computer talents
puts(m3);
gets(name);
printf("Well, %s, %sn", name, MSG);
printf("%sn%sn", m1, m2);
gets(talents);
puts("Let's see if I've got that list:");
puts(talents);
printf("Thanks for the information, %s.n", name);
return 0;
}
Output
Hi! I'm Clyde the Computer. I have many talents.
Let me tell you some of them.
What were they? Ah, yes, here's a partial list.
Adding numbers swiftly
Multiplying accurately
Stashing data
Following instructions to the letter
Understanding the C language
Enough about me –– what's your name?
Nigel Barntwit
Well, Nigel Barntwit, You must have many talents. Tell me
some.
Just limit yourself to one line's worth.
If you can't think of anything, fake it.
Fencing, yodeling, malingering, cheese tasting, and sighing.
Let's see if I've got that list:
Fencing, yodeling, malingering, cheese tasting, and sighing.
Thanks for the information, Nigel Barntwit.
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.
#include <stdio.h>
int main(void)
{
printf("%s, %p, %cn", "We", "are", *"space farers");
return 0;
}
Output
We, 0x0040c010, s
Array and Pointer Differences
Let's examine 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?
Arrays of Character Strings
const char *mytal[LIM] = {"Adding numbers swiftly",
"Multiplying accurately", "Stashing data",
"Following instructions to the letter",
"Understanding the C language"};
Let's study this declaration. 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
Rectangular versus ragged array
The gets() Function
The gets() (get string) function is very handy for interactive programs. It gets a
string from your system's standard input device, normally your keyboard. Because a
string has no predetermined length, gets() needs a way to know when to stop. Its
method is to read characters until it reaches a newline (n) character, which you
generate by pressing the Enter key. It takes all the characters up to (but not
including) the newline, tacks on a null character (0), and gives the string to the
calling program. The newline character itself is read and discarded so that the next
read begins at the start of the next line.
#include <stdio.h>
#define MAX 81
int main(void)
{
char name[MAX]; /* allot space */
printf("Hi, what's your name?n");
gets(name); /* place string into name array */
printf("Nice name, %s.n", name);
return 0;
}
Output
Hi, what's your name?
The Mysterious Davina D'Lema
Nice name, The Mysterious Davina D'Lema
#include <stdio.h>
#define MAX 81
int main(void)
{
char name[MAX];
char * ptr;
printf("Hi, what's your name?n");
ptr = gets(name);
printf("%s? Ah! %s!n", name, ptr);
return 0;
}
Output
Hi, what's your name?
Wellington Snackworthy
Wellington Snackworthy? Ah! Wellington Snackworthy!
The fgets() Function
One weakness of gets() is that it doesn't check to see whether the input actually fits
into the reserved storage area. Extra characters simply overflow into the adjoining
memory. The fgets() function improves on this questionable behavior by enabling you
to specify an upper limit for the number of characters to be read. Because fgets() is
designed for file I/O, it's slightly more awkward than gets() for keyboard input. It
differs from gets() in three respects:
• 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.
• If fgets() reads the newline, it stores it in the string, unlike gets(), which discards
it.
• 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
#include <stdio.h>
#define MAX 81
int main(void)
{
char name[MAX];
char * ptr;
printf("Hi, what's your name?n");
ptr = fgets(name, MAX, stdin);
printf("%s? Ah! %s!n", name, ptr);
return 0;
}
Output
Hi, what's your name?
Jon Dough
Jon Dough
? Ah! Jon Dough
!
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
#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.
he puts() Function
The puts() function is very easy to use. Just give it the address of a string for an
argument.
It stops when it encounters the null character
#include <stdio.h>
#define DEF "I am a #defined string.“
int main(void)
{
char str1[80] = "An array was initialized to me.";
const char * str2 = "A pointer was initialized to me.";
puts("I'm an argument to puts().");
puts(DEF);
puts(str1);
puts(str2);
puts(&str1[5]);
puts(str2+4);
return 0;
}
Output
I'm an argument to puts().
I am a #defined string.
An array was initialized to me.
A pointer was initialized to me.
ray was initialized to me.
inter was initialized to me.
#include <stdio.h>
int main(void)
{
char side_a[] = "Side A";
char dont[] = {'W', 'O', 'W', '!' };
char side_b[] = "Side B";
puts(dont); /* dont is not a string */
return 0;
}
Output
WOW!Side A
The fputs() Function
The fputs() function is the file-oriented version of puts(). The main differences are these:
• The fputs() function takes a second argument indicating the file to which to write. You
can use stdout (for standard output), which is defined in stdio.h, as an argument to
output to your display.
• Unlike puts(), fputs() does not automatically append a newline to the output.
Note that gets() discards a newline on input, but puts() adds a newline on output. On the
other hand, fgets() stores the newline on input, and fputs() doesn't add a newline on
output.
The Do-It-Yourself Option
#include <stdio.h>
void put1(const char * string) /* string not altered */
{
while (*string != '0')
putchar(*string++);
}
String 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.
The strlen() Function
The strlen() function, as you already know, finds the length of a string. It's used in the next
example, a function that shortens lengthy strings:
/* 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.
#include <stdio.h>
#include <string.h> /* contains string function prototypes */
void fit(char *, unsigned int);
int main(void)
{
char mesg[] = "Things should be as simple as possible,"
" but not simpler.";
puts(mesg);
fit(mesg,38);
puts(mesg);
puts("Let's look at some more of the string.");
puts(mesg + 39);
return 0;
}
void fit(char *string, unsigned int size)
{
if (strlen(string) > size)
*(string + size) = '0';
}
Output
Things should be as simple as possible, but not simpler.
Things should be as simple as possible
Let's look at some more of the string.
but not simpler.
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. Function strcat() is type char * (that is, a
pointer-to-char). It returns the value of its first argument—the address of the first
character of the string to which the second string is appended
#include <stdio.h>
#include <string.h> /* declares the strcat() function */
#define SIZE 80
int main(void)
{
char flower[SIZE];
char addon[] = "s smell like old shoes.";
puts("What is your favorite flower?");
gets(flower);
strcat(flower, addon);
puts(flower);
puts(addon);
return 0;
}
Output
What is your favorite flower?
Rose
Roses smell like old shoes.
s smell like old shoes.
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.
#include <stdio.h>
#include <string.h>
#define SIZE 30
#define BUGSIZE 13
int main(void)
{
char flower[SIZE];
char addon[] = "s smell like old shoes.";
char bug[BUGSIZE];
int available;
puts("What is your favorite flower?");
gets(flower);
if ((strlen(addon) + strlen(flower) + 1) <= SIZE)
strcat(flower, addon);
puts(flower);
puts("What is your favorite bug?");
gets(bug);
available = BUGSIZE - strlen(bug) - 1;
strncat(bug, addon, available);
puts(bug);
return 0;
}
Output
What is your favorite flower?
Rose
Roses smell like old shoes.
What is your favorite bug?
Aphid
Aphids smell
The strcmp() Function
Suppose you want to compare someone's response to a stored string, as shown:
// it works ?
#include <stdio.h>
#define ANSWER "Grant“
int main(void)
{
char try[40];
puts("Who is buried in Grant's tomb?");
gets(try);
while (try != ANSWER)
{
puts("No, that's wrong. Try again.");
gets(try);
}
puts("That's right!");
return 0;
}
#include <stdio.h>
#include <string.h> /* declares strcmp() */
#define ANSWER "Grant"
#define MAX 40
int main(void)
{
char try[MAX];
puts("Who is buried in Grant's tomb?");
gets(try);
while (strcmp(try,ANSWER) != 0)
{
puts("No, that's wrong. Try again.");
gets(try);
}
puts("That's right!");
return 0;
}
What value does strcmp() return if the strings are not the same?
#include <stdio.h>
#include <string.h>
int main(void)
{
printf("strcmp("A", "A") is ");
printf("%dn", strcmp("A", "A"));
printf("strcmp("A", "B") is ");
printf("%dn", strcmp("A", "B"));
printf("strcmp("B", "A") is ");
printf("%dn", strcmp("B", "A"));
printf("strcmp("C", "A") is ");
printf("%dn", strcmp("C", "A"));
printf("strcmp("Z", "a") is ");
printf("%dn", strcmp("Z", "a"));
printf("strcmp("apples", "apple") is ");
printf("%dn", strcmp("apples", "apple"));
return 0;
}
The strcmp() Return Value
Output
strcmp("A", "A") is 0
strcmp("A", "B") is -1
strcmp("B", "A") is 1
strcmp("C", "A") is 1
strcmp("Z", "a") is -1
strcmp("apples", "apple") is 1
The strcmp() function compares strings until it finds corresponding characters that
differ, which could take the search to the end of one of the strings. The strncmp()
function compares the strings until they differ or until it has compared a number of
characters specified by a third argument. For example, if you wanted to search for
strings that begin with "astro", you could limit the search to the first five characters.
The strncmp() Variation
#include <stdio.h>
#include <string.h>
#define LISTSIZE 5
int main()
{
const char * list[LISTSIZE] =
{
"astronomy", "astounding",
"astrophysics", "ostracize",
"asterism"
};
int count = 0;
int i;
for (i = 0; i < LISTSIZE; i++)
if (strncmp(list[i],"astro", 5) == 0)
{
printf("Found: %sn", list[i]);
count++;
}
printf("The list contained %d words beginning"
" with astro.n", count);
return 0;
}
Output
Found: astronomy
Found: astrophysics
The list contained 2 words beginning with astro.
strcpy():
copies the C string pointed by source into the array pointed by destination, including
the terminating null character (and stopping at that point).
To avoid overflows, the size of the array pointed by destination shall be long enough to
contain the same C string as source (including the terminating null character), and
should not overlap in memory with source.
strncpy():
Copies the first num characters of source to destination. If the end of the source C
string (which is signaled by a null-character) is found before num characters have
been copied, destination is padded with zeros until a total of num characters have
been written to it.
No null-character is implicitly appended at the end of destination if source is longer
than num. Thus, in this case, destination shall not be considered a null terminated C
string (reading it as such would overflow)
The strcpy() and strncpy() Functions
#include <stdio.h>
#include <string.h> /* declares strcpy() */
#define SIZE 40
#define LIM 5
int main(void)
{
char qwords[LIM][SIZE];
char temp[SIZE];
int i = 0;
printf("Enter %d words beginning with q:n", LIM);
while (i < LIM && gets(temp))
{
if (temp[0] != 'q')
printf("%s doesn't begin with q!n", temp);
else {
strcpy(qwords[i], temp);
i++;
}
}
puts("Here are the words accepted:");
for (i = 0; i < LIM; i++)
puts(qwords[i]);
return 0;
}
Output
Enter 5 words beginning with q:
quackery
quasar
quilt
quotient
no more
no more doesn't begin with q!
quiz
Here are the words accepted:
quackery
quasar
quilt
quotient
quiz
#include <stdio.h>
#include <string.h> /* declares strncpy() */
#define SIZE 40
#define TARGSIZE 7
#define LIM 5
int main(void)
{
char qwords[LIM][TARGSIZE];
char temp[SIZE];
int i = 0;
printf("Enter %d words beginning with q:n", LIM);
while (i < LIM && gets(temp))
{
if (temp[0] != 'q')
printf("%s doesn't begin with q!n", temp);
else
{
strncpy(qwords[i], temp, TARGSIZE - 1);
qwords[i][TARGSIZE - 1] = '0';
i++;
}
}
puts("Here are the words accepted:");
for (i = 0; i < LIM; i++)
puts(qwords[i]);
return 0;
}
Output
Enter 5 words beginning with q:
quack
quadratic
quisling
quota
quagga
Here are the words accepted:
quack
quadra
quisli
quota
quagga
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
The sprintf() Function
#include <stdio.h>
#define MAX 20
int main(void)
{
char first[MAX];
char last[MAX];
char formal[2 * MAX + 10];
double prize;
puts("Enter your first name:");
gets(first);
puts("Enter your last name:");
gets(last);
puts("Enter your prize money:");
scanf("%lf", &prize);
sprintf(formal, "%s, %-19s: $%6.2fn", last, first, prize);
puts(formal);
return 0;
}
Output
Enter your first name:
Teddy
Enter your last name:
Behr
Enter your prize money:
2000
Behr, Teddy : $2000.00
#include <stdio.h>
#include <string.h>
#define SIZE 81 /* string length limit, including 0 */
#define LIM 20 /* maximum number of lines to be read */
#define HALT "" /* null string to stop input */
void stsrt(char *strings[], int num);/* string-sort function */
int main(void)
{
char input[LIM][SIZE]; /* array to store input */
char *ptstr[LIM]; /* array of pointer variables */
int ct = 0; /* input count */
int k; /* output count */
printf("Input up to %d lines, and I will sort them.n",LIM);
printf("To stop, press the Enter key at a line's start.n");
while (ct < LIM && gets(input[ct]) != NULL
&& input[ct][0] != '0')
{
ptstr[ct] = input[ct]; /* set ptrs to strings */
ct++;
}
stsrt(ptstr, ct); /* string sorter */
puts("nHere's the sorted list:n");
for (k = 0; k < ct; k++)
puts(ptstr[k]) ; /* sorted pointers */
return 0;
}
/* string-pointer-sorting function */
void stsrt(char *strings[], int num)
{
char *temp;
int top, seek;
for (top = 0; top < num-1; top++)
for (seek = top + 1; seek < num; seek++)
if (strcmp(strings[top],strings[seek]) > 0)
{
temp = strings[top];
strings[top] = strings[seek];
strings[seek] = temp;
}
}
Output
Input up to 20 lines, and I will sort them.
To stop, press the Enter key at a line's start.
O that I was where I would be,
Then would I be where I am not;
But where I am I must be,
And where I would be I can not.
Here's the sorted list:
And where I would be I can not.
But where I am I must be,
O that I was where I would be,
Then would I be where I am not;
The Selection Sort Algorithm
To sort the pointers, we use the selection sort algorithm. The idea is to use a for loop
to compare each element in turn with the first element. If the compared element
precedes the current first element, the program swaps the two. By the time the
program reaches the end of the loop, the first element contains a pointer to whichever
string is first in the machine collating sequence. Then the outer for loop repeats the
process, this time starting with the second element of input. When the inner loop
completes, the pointer to the second-ranking string ends up in the second element of
ptrst. The process continues until all the elements have been sorted.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LIMIT 80
void ToUpper(char *);
int PunctCount(const char *);
int main(void)
{
char line[LIMIT];
puts("Please enter a line:");
gets(line);
ToUpper(line);
puts(line);
printf("That line has %d punctuation characters.n",
PunctCount(line));
return 0;
}
void ToUpper(char * str)
{
while (*str)
{
*str = toupper(*str);
str++;
}
}
int PunctCount(const char * str)
{
int ct = 0;
while (*str)
{
if (ispunct(*str))
ct++;
str++;
}
return ct;
}
Output
Please enter a line:
Me? You talkin' to me? Get outta here!
ME? YOU TALKIN' TO ME? GET OUTTA HERE!
That line has 4 punctuation characters.
Command-Line Arguments
Before the modern graphical interface, there was the command-line interface. DOS
and Unix are examples. The command line is the line you type to run your program in
a command-line environment. Suppose you have a program in a file named fuss. Then
the command line to run it might look like this in Unix:
#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;
}
Running the program: C>repeat Resistance is futile
Output
The command line has 3 arguments:
1: Resistance
2: is
3: futile
#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!
#include <stdio.h>
#include <stdlib.h>
int main()
{
char number[30];
char * end;
long value;
puts("Enter a number (empty line to quit):");
while(gets(number) && number[0] != '0')
{
value = strtol(number, &end, 10); /* base 10 */
printf("value: %ld, stopped at %s (%d)n",
value, end, *end);
value = strtol(number, &end, 16); /* base 16 */
printf("value: %ld, stopped at %s (%d)n",
value, end, *end);
puts("Next number:");
}
puts("Bye!n");
return 0;
}
Output
Enter a number (empty line to quit):
10
value: 10, stopped at (0)
value: 16, stopped at (0)
Next number:
10atom
value: 10, stopped at atom (97)
value: 266, stopped at tom (116)
Next number:
Bye!

More Related Content

PDF
8 arrays and pointers
MomenMostafa
 
PDF
6 c control statements branching &amp; jumping
MomenMostafa
 
PDF
4 operators, expressions &amp; statements
MomenMostafa
 
PDF
7 functions
MomenMostafa
 
PDF
1 introducing c language
MomenMostafa
 
PPTX
Decision making and branching
Saranya saran
 
PPTX
Expressions using operator in c
Saranya saran
 
DOCX
C interview question answer 2
Amit Kapoor
 
8 arrays and pointers
MomenMostafa
 
6 c control statements branching &amp; jumping
MomenMostafa
 
4 operators, expressions &amp; statements
MomenMostafa
 
7 functions
MomenMostafa
 
1 introducing c language
MomenMostafa
 
Decision making and branching
Saranya saran
 
Expressions using operator in c
Saranya saran
 
C interview question answer 2
Amit Kapoor
 

What's hot (20)

PPT
Unit 5 Foc
JAYA
 
PPT
Functions and pointers_unit_4
MKalpanaDevi
 
PPTX
C Programming Language Part 6
Rumman Ansari
 
PPT
Buffer OverFlow
Rambabu Duddukuri
 
PDF
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
DOCX
Core programming in c
Rahul Pandit
 
DOCX
Python unit 3 and Unit 4
Anandh Arumugakan
 
PPT
Mesics lecture 5 input – output in ‘c’
eShikshak
 
DOC
C tech questions
vijay00791
 
PPT
Lecture 10 - Control Structures 2
Md. Imran Hossain Showrov
 
PPT
Lecture 8- Data Input and Output
Md. Imran Hossain Showrov
 
PPTX
C Programming Language Part 8
Rumman Ansari
 
PPT
An imperative study of c
Tushar B Kute
 
PPTX
C Programming Language Part 9
Rumman Ansari
 
PDF
C programming
Samsil Arefin
 
PDF
Functions
SANTOSH RATH
 
PPT
Lecture 12 - Recursion
Md. Imran Hossain Showrov
 
PPTX
Programming ppt files (final)
yap_raiza
 
PPTX
C Programming Language Part 11
Rumman Ansari
 
PDF
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
ssuserd6b1fd
 
Unit 5 Foc
JAYA
 
Functions and pointers_unit_4
MKalpanaDevi
 
C Programming Language Part 6
Rumman Ansari
 
Buffer OverFlow
Rambabu Duddukuri
 
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
Core programming in c
Rahul Pandit
 
Python unit 3 and Unit 4
Anandh Arumugakan
 
Mesics lecture 5 input – output in ‘c’
eShikshak
 
C tech questions
vijay00791
 
Lecture 10 - Control Structures 2
Md. Imran Hossain Showrov
 
Lecture 8- Data Input and Output
Md. Imran Hossain Showrov
 
C Programming Language Part 8
Rumman Ansari
 
An imperative study of c
Tushar B Kute
 
C Programming Language Part 9
Rumman Ansari
 
C programming
Samsil Arefin
 
Functions
SANTOSH RATH
 
Lecture 12 - Recursion
Md. Imran Hossain Showrov
 
Programming ppt files (final)
yap_raiza
 
C Programming Language Part 11
Rumman Ansari
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
ssuserd6b1fd
 
Ad

Similar to 9 character string &amp; string library (20)

PDF
String notes
Prasadu Peddi
 
PPTX
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
PPTX
introduction to strings in c programming
mikeymanjiro2090
 
PDF
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
PPT
Strings in c
vampugani
 
PPTX
C-Arrays & Strings (computer programming).pptx
yusuph2410
 
PPTX
COm1407: Character & Strings
Hemantha Kulathilake
 
PPT
14 strings
Rohit Shrivastava
 
PDF
Data structure week 3
karmuhtam
 
PPTX
POEPPSGNHwkejnkweoewnkenjwjewkjewoewkjewijewjk
hanumanthumanideeph6
 
PDF
Principals of Programming in CModule -5.pdfModule-4.pdf
anilcsbs
 
PPTX
Lecture_on_string_manipulation_functions.pptx
ABHISRIVASTAV9
 
PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
PPT
THE FORMAT AND USAGE OF STRINGS IN C.PPT
shanthabalaji2013
 
PPT
Strings
Imad Ali
 
PPT
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
PPTX
UNIT 4C-Strings.pptx for c language and basic knowledge
2024163103shubham
 
PPT
Strings
Mitali Chugh
 
PPTX
Lecture 2. mte 407
rumanatasnim415
 
String notes
Prasadu Peddi
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
introduction to strings in c programming
mikeymanjiro2090
 
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
Strings in c
vampugani
 
C-Arrays & Strings (computer programming).pptx
yusuph2410
 
COm1407: Character & Strings
Hemantha Kulathilake
 
14 strings
Rohit Shrivastava
 
Data structure week 3
karmuhtam
 
POEPPSGNHwkejnkweoewnkenjwjewkjewoewkjewijewjk
hanumanthumanideeph6
 
Principals of Programming in CModule -5.pdfModule-4.pdf
anilcsbs
 
Lecture_on_string_manipulation_functions.pptx
ABHISRIVASTAV9
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
THE FORMAT AND USAGE OF STRINGS IN C.PPT
shanthabalaji2013
 
Strings
Imad Ali
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
UNIT 4C-Strings.pptx for c language and basic knowledge
2024163103shubham
 
Strings
Mitali Chugh
 
Lecture 2. mte 407
rumanatasnim415
 
Ad

More from MomenMostafa (7)

PDF
5 c control statements looping
MomenMostafa
 
PDF
2 data and c
MomenMostafa
 
PDF
3 character strings and formatted input output
MomenMostafa
 
PDF
Storage classes, linkage & memory management
MomenMostafa
 
PDF
C programming & data structure [character strings & string functions]
MomenMostafa
 
PDF
C programming & data structure [arrays & pointers]
MomenMostafa
 
PPTX
Embedded System Practical Workshop using the ARM Processor
MomenMostafa
 
5 c control statements looping
MomenMostafa
 
2 data and c
MomenMostafa
 
3 character strings and formatted input output
MomenMostafa
 
Storage classes, linkage & memory management
MomenMostafa
 
C programming & data structure [character strings & string functions]
MomenMostafa
 
C programming & data structure [arrays & pointers]
MomenMostafa
 
Embedded System Practical Workshop using the ARM Processor
MomenMostafa
 

Recently uploaded (20)

PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PPTX
Save Business Costs with CRM Software for Insurance Agents
Insurance Tech Services
 
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PPTX
AIRLINE PRICE API | FLIGHT API COST |
philipnathen82
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
RanuFajar1
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
Michael624841
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Save Business Costs with CRM Software for Insurance Agents
Insurance Tech Services
 
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
Exploring AI Agents in Process Industries
amoreira6
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
AIRLINE PRICE API | FLIGHT API COST |
philipnathen82
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Materi_Pemrograman_Komputer-Looping.pptx
RanuFajar1
 
oapresentation.pptx
mehatdhavalrajubhai
 
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
A REACT POMODORO TIMER WEB APPLICATION.pdf
Michael624841
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 

9 character string &amp; string library

  • 2. Character Strings and String Functions
  • 3. #include <stdio.h> #define MSG "You must have many talents. Tell me some." // a symbolic string constant #define LIM 5 #define LINELEN 81 // maximum string length + 1 int main(void) { char name[LINELEN]; char talents[LINELEN]; int i; // initializing a dimensioned char array const char m1[40] = "Limit yourself to one line's worth."; // letting the compiler compute the array size const char m2[] = "If you can't think of anything, fake it."; const char *m3 = "nEnough about me -- what's your name?"; // initializing a pointer // initializing an array of string pointers const char *mytal[LIM] = { // array of 5 pointers "Adding numbers swiftly", "Multiplying accurately", "Stashing data", "Following instructions to the letter", "Understanding the C language" };
  • 4. printf("Hi! I'm Clyde the Computer." " I have many talents.n"); printf("Let me tell you some of them.n"); puts("What were they? Ah, yes, here's a partial list."); for (i = 0; i < LIM; i++) puts(mytal[i]); // print list of computer talents puts(m3); gets(name); printf("Well, %s, %sn", name, MSG); printf("%sn%sn", m1, m2); gets(talents); puts("Let's see if I've got that list:"); puts(talents); printf("Thanks for the information, %s.n", name); return 0; }
  • 5. Output Hi! I'm Clyde the Computer. I have many talents. Let me tell you some of them. What were they? Ah, yes, here's a partial list. Adding numbers swiftly Multiplying accurately Stashing data Following instructions to the letter Understanding the C language Enough about me –– what's your name? Nigel Barntwit Well, Nigel Barntwit, You must have many talents. Tell me some. Just limit yourself to one line's worth. If you can't think of anything, fake it. Fencing, yodeling, malingering, cheese tasting, and sighing. Let's see if I've got that list: Fencing, yodeling, malingering, cheese tasting, and sighing. Thanks for the information, Nigel Barntwit.
  • 6. 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.
  • 7. #include <stdio.h> int main(void) { printf("%s, %p, %cn", "We", "are", *"space farers"); return 0; }
  • 9. Array and Pointer Differences Let's examine 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?
  • 10. Arrays of Character Strings const char *mytal[LIM] = {"Adding numbers swiftly", "Multiplying accurately", "Stashing data", "Following instructions to the letter", "Understanding the C language"}; Let's study this declaration. 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
  • 12. The gets() Function The gets() (get string) function is very handy for interactive programs. It gets a string from your system's standard input device, normally your keyboard. Because a string has no predetermined length, gets() needs a way to know when to stop. Its method is to read characters until it reaches a newline (n) character, which you generate by pressing the Enter key. It takes all the characters up to (but not including) the newline, tacks on a null character (0), and gives the string to the calling program. The newline character itself is read and discarded so that the next read begins at the start of the next line.
  • 13. #include <stdio.h> #define MAX 81 int main(void) { char name[MAX]; /* allot space */ printf("Hi, what's your name?n"); gets(name); /* place string into name array */ printf("Nice name, %s.n", name); return 0; }
  • 14. Output Hi, what's your name? The Mysterious Davina D'Lema Nice name, The Mysterious Davina D'Lema
  • 15. #include <stdio.h> #define MAX 81 int main(void) { char name[MAX]; char * ptr; printf("Hi, what's your name?n"); ptr = gets(name); printf("%s? Ah! %s!n", name, ptr); return 0; }
  • 16. Output Hi, what's your name? Wellington Snackworthy Wellington Snackworthy? Ah! Wellington Snackworthy!
  • 17. The fgets() Function One weakness of gets() is that it doesn't check to see whether the input actually fits into the reserved storage area. Extra characters simply overflow into the adjoining memory. The fgets() function improves on this questionable behavior by enabling you to specify an upper limit for the number of characters to be read. Because fgets() is designed for file I/O, it's slightly more awkward than gets() for keyboard input. It differs from gets() in three respects: • 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. • If fgets() reads the newline, it stores it in the string, unlike gets(), which discards it. • 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
  • 18. #include <stdio.h> #define MAX 81 int main(void) { char name[MAX]; char * ptr; printf("Hi, what's your name?n"); ptr = fgets(name, MAX, stdin); printf("%s? Ah! %s!n", name, ptr); return 0; }
  • 19. Output Hi, what's your name? Jon Dough Jon Dough ? Ah! Jon Dough !
  • 20. 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
  • 21. #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; }
  • 22. 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.
  • 23. he puts() Function The puts() function is very easy to use. Just give it the address of a string for an argument. It stops when it encounters the null character
  • 24. #include <stdio.h> #define DEF "I am a #defined string.“ int main(void) { char str1[80] = "An array was initialized to me."; const char * str2 = "A pointer was initialized to me."; puts("I'm an argument to puts()."); puts(DEF); puts(str1); puts(str2); puts(&str1[5]); puts(str2+4); return 0; }
  • 25. Output I'm an argument to puts(). I am a #defined string. An array was initialized to me. A pointer was initialized to me. ray was initialized to me. inter was initialized to me.
  • 26. #include <stdio.h> int main(void) { char side_a[] = "Side A"; char dont[] = {'W', 'O', 'W', '!' }; char side_b[] = "Side B"; puts(dont); /* dont is not a string */ return 0; }
  • 28. The fputs() Function The fputs() function is the file-oriented version of puts(). The main differences are these: • The fputs() function takes a second argument indicating the file to which to write. You can use stdout (for standard output), which is defined in stdio.h, as an argument to output to your display. • Unlike puts(), fputs() does not automatically append a newline to the output. Note that gets() discards a newline on input, but puts() adds a newline on output. On the other hand, fgets() stores the newline on input, and fputs() doesn't add a newline on output.
  • 29. The Do-It-Yourself Option #include <stdio.h> void put1(const char * string) /* string not altered */ { while (*string != '0') putchar(*string++); }
  • 30. String 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.
  • 31. The strlen() Function The strlen() function, as you already know, finds the length of a string. It's used in the next example, a function that shortens lengthy strings: /* 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.
  • 32. #include <stdio.h> #include <string.h> /* contains string function prototypes */ void fit(char *, unsigned int); int main(void) { char mesg[] = "Things should be as simple as possible," " but not simpler."; puts(mesg); fit(mesg,38); puts(mesg); puts("Let's look at some more of the string."); puts(mesg + 39); return 0; } void fit(char *string, unsigned int size) { if (strlen(string) > size) *(string + size) = '0'; }
  • 33. Output Things should be as simple as possible, but not simpler. Things should be as simple as possible Let's look at some more of the string. but not simpler.
  • 34. 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. Function strcat() is type char * (that is, a pointer-to-char). It returns the value of its first argument—the address of the first character of the string to which the second string is appended
  • 35. #include <stdio.h> #include <string.h> /* declares the strcat() function */ #define SIZE 80 int main(void) { char flower[SIZE]; char addon[] = "s smell like old shoes."; puts("What is your favorite flower?"); gets(flower); strcat(flower, addon); puts(flower); puts(addon); return 0; }
  • 36. Output What is your favorite flower? Rose Roses smell like old shoes. s smell like old shoes.
  • 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.
  • 38. #include <stdio.h> #include <string.h> #define SIZE 30 #define BUGSIZE 13 int main(void) { char flower[SIZE]; char addon[] = "s smell like old shoes."; char bug[BUGSIZE]; int available; puts("What is your favorite flower?"); gets(flower); if ((strlen(addon) + strlen(flower) + 1) <= SIZE) strcat(flower, addon); puts(flower); puts("What is your favorite bug?"); gets(bug); available = BUGSIZE - strlen(bug) - 1; strncat(bug, addon, available); puts(bug); return 0; }
  • 39. Output What is your favorite flower? Rose Roses smell like old shoes. What is your favorite bug? Aphid Aphids smell
  • 40. The strcmp() Function Suppose you want to compare someone's response to a stored string, as shown: // it works ? #include <stdio.h> #define ANSWER "Grant“ int main(void) { char try[40]; puts("Who is buried in Grant's tomb?"); gets(try); while (try != ANSWER) { puts("No, that's wrong. Try again."); gets(try); } puts("That's right!"); return 0; }
  • 41. #include <stdio.h> #include <string.h> /* declares strcmp() */ #define ANSWER "Grant" #define MAX 40 int main(void) { char try[MAX]; puts("Who is buried in Grant's tomb?"); gets(try); while (strcmp(try,ANSWER) != 0) { puts("No, that's wrong. Try again."); gets(try); } puts("That's right!"); return 0; }
  • 42. What value does strcmp() return if the strings are not the same? #include <stdio.h> #include <string.h> int main(void) { printf("strcmp("A", "A") is "); printf("%dn", strcmp("A", "A")); printf("strcmp("A", "B") is "); printf("%dn", strcmp("A", "B")); printf("strcmp("B", "A") is "); printf("%dn", strcmp("B", "A")); printf("strcmp("C", "A") is "); printf("%dn", strcmp("C", "A")); printf("strcmp("Z", "a") is "); printf("%dn", strcmp("Z", "a")); printf("strcmp("apples", "apple") is "); printf("%dn", strcmp("apples", "apple")); return 0; } The strcmp() Return Value
  • 43. Output strcmp("A", "A") is 0 strcmp("A", "B") is -1 strcmp("B", "A") is 1 strcmp("C", "A") is 1 strcmp("Z", "a") is -1 strcmp("apples", "apple") is 1
  • 44. The strcmp() function compares strings until it finds corresponding characters that differ, which could take the search to the end of one of the strings. The strncmp() function compares the strings until they differ or until it has compared a number of characters specified by a third argument. For example, if you wanted to search for strings that begin with "astro", you could limit the search to the first five characters. The strncmp() Variation
  • 45. #include <stdio.h> #include <string.h> #define LISTSIZE 5 int main() { const char * list[LISTSIZE] = { "astronomy", "astounding", "astrophysics", "ostracize", "asterism" }; int count = 0; int i; for (i = 0; i < LISTSIZE; i++) if (strncmp(list[i],"astro", 5) == 0) { printf("Found: %sn", list[i]); count++; } printf("The list contained %d words beginning" " with astro.n", count); return 0; }
  • 46. Output Found: astronomy Found: astrophysics The list contained 2 words beginning with astro.
  • 47. strcpy(): copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source. strncpy(): Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it. No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow) The strcpy() and strncpy() Functions
  • 48. #include <stdio.h> #include <string.h> /* declares strcpy() */ #define SIZE 40 #define LIM 5 int main(void) { char qwords[LIM][SIZE]; char temp[SIZE]; int i = 0; printf("Enter %d words beginning with q:n", LIM); while (i < LIM && gets(temp)) { if (temp[0] != 'q') printf("%s doesn't begin with q!n", temp); else { strcpy(qwords[i], temp); i++; } } puts("Here are the words accepted:"); for (i = 0; i < LIM; i++) puts(qwords[i]); return 0; }
  • 49. Output Enter 5 words beginning with q: quackery quasar quilt quotient no more no more doesn't begin with q! quiz Here are the words accepted: quackery quasar quilt quotient quiz
  • 50. #include <stdio.h> #include <string.h> /* declares strncpy() */ #define SIZE 40 #define TARGSIZE 7 #define LIM 5 int main(void) { char qwords[LIM][TARGSIZE]; char temp[SIZE]; int i = 0; printf("Enter %d words beginning with q:n", LIM); while (i < LIM && gets(temp)) { if (temp[0] != 'q') printf("%s doesn't begin with q!n", temp);
  • 51. else { strncpy(qwords[i], temp, TARGSIZE - 1); qwords[i][TARGSIZE - 1] = '0'; i++; } } puts("Here are the words accepted:"); for (i = 0; i < LIM; i++) puts(qwords[i]); return 0; }
  • 52. Output Enter 5 words beginning with q: quack quadratic quisling quota quagga Here are the words accepted: quack quadra quisli quota quagga
  • 53. 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 The sprintf() Function
  • 54. #include <stdio.h> #define MAX 20 int main(void) { char first[MAX]; char last[MAX]; char formal[2 * MAX + 10]; double prize; puts("Enter your first name:"); gets(first); puts("Enter your last name:"); gets(last); puts("Enter your prize money:"); scanf("%lf", &prize); sprintf(formal, "%s, %-19s: $%6.2fn", last, first, prize); puts(formal); return 0; }
  • 55. Output Enter your first name: Teddy Enter your last name: Behr Enter your prize money: 2000 Behr, Teddy : $2000.00
  • 56. #include <stdio.h> #include <string.h> #define SIZE 81 /* string length limit, including 0 */ #define LIM 20 /* maximum number of lines to be read */ #define HALT "" /* null string to stop input */ void stsrt(char *strings[], int num);/* string-sort function */ int main(void) { char input[LIM][SIZE]; /* array to store input */ char *ptstr[LIM]; /* array of pointer variables */ int ct = 0; /* input count */ int k; /* output count */ printf("Input up to %d lines, and I will sort them.n",LIM); printf("To stop, press the Enter key at a line's start.n");
  • 57. while (ct < LIM && gets(input[ct]) != NULL && input[ct][0] != '0') { ptstr[ct] = input[ct]; /* set ptrs to strings */ ct++; } stsrt(ptstr, ct); /* string sorter */ puts("nHere's the sorted list:n"); for (k = 0; k < ct; k++) puts(ptstr[k]) ; /* sorted pointers */ return 0; }
  • 58. /* string-pointer-sorting function */ void stsrt(char *strings[], int num) { char *temp; int top, seek; for (top = 0; top < num-1; top++) for (seek = top + 1; seek < num; seek++) if (strcmp(strings[top],strings[seek]) > 0) { temp = strings[top]; strings[top] = strings[seek]; strings[seek] = temp; } }
  • 59. Output Input up to 20 lines, and I will sort them. To stop, press the Enter key at a line's start. O that I was where I would be, Then would I be where I am not; But where I am I must be, And where I would be I can not. Here's the sorted list: And where I would be I can not. But where I am I must be, O that I was where I would be, Then would I be where I am not;
  • 60. The Selection Sort Algorithm To sort the pointers, we use the selection sort algorithm. The idea is to use a for loop to compare each element in turn with the first element. If the compared element precedes the current first element, the program swaps the two. By the time the program reaches the end of the loop, the first element contains a pointer to whichever string is first in the machine collating sequence. Then the outer for loop repeats the process, this time starting with the second element of input. When the inner loop completes, the pointer to the second-ranking string ends up in the second element of ptrst. The process continues until all the elements have been sorted.
  • 61. #include <stdio.h> #include <string.h> #include <ctype.h> #define LIMIT 80 void ToUpper(char *); int PunctCount(const char *); int main(void) { char line[LIMIT]; puts("Please enter a line:"); gets(line); ToUpper(line); puts(line); printf("That line has %d punctuation characters.n", PunctCount(line)); return 0; }
  • 62. void ToUpper(char * str) { while (*str) { *str = toupper(*str); str++; } } int PunctCount(const char * str) { int ct = 0; while (*str) { if (ispunct(*str)) ct++; str++; } return ct; }
  • 63. Output Please enter a line: Me? You talkin' to me? Get outta here! ME? YOU TALKIN' TO ME? GET OUTTA HERE! That line has 4 punctuation characters.
  • 64. Command-Line Arguments Before the modern graphical interface, there was the command-line interface. DOS and Unix are examples. The command line is the line you type to run your program in a command-line environment. Suppose you have a program in a file named fuss. Then the command line to run it might look like this in Unix:
  • 65. #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; } Running the program: C>repeat Resistance is futile
  • 66. Output The command line has 3 arguments: 1: Resistance 2: is 3: futile
  • 67. #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; }
  • 68. Output % hello 3 Hello, good looking! Hello, good looking! Hello, good looking!
  • 69. #include <stdio.h> #include <stdlib.h> int main() { char number[30]; char * end; long value; puts("Enter a number (empty line to quit):"); while(gets(number) && number[0] != '0') { value = strtol(number, &end, 10); /* base 10 */ printf("value: %ld, stopped at %s (%d)n", value, end, *end); value = strtol(number, &end, 16); /* base 16 */ printf("value: %ld, stopped at %s (%d)n", value, end, *end); puts("Next number:"); } puts("Bye!n"); return 0; }
  • 70. Output Enter a number (empty line to quit): 10 value: 10, stopped at (0) value: 16, stopped at (0) Next number: 10atom value: 10, stopped at atom (97) value: 266, stopped at tom (116) Next number: Bye!