















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to character strings and their manipulation in c programming language. It covers the declaration and initialization of character strings, the use of string i/o library routines, and string handling library routines such as copying, concatenating, finding length, and comparing strings. The document also explains how to pass an array to a function and sorts strings using an array of pointers.
Typology: Slides
1 / 23
This page cannot be seen from the preview
Don't miss anything!
















Lecture 16
char color [ ] = "scarlet" ; or char *colorPtr = "scarlet" ; or char color [8] = {'s', 'c', 'a', 'r', 'l', 'e', 't', '\0'} ;
/* The following are function prototypes for some of the String I/O and Handling Library Routines */
/* Input next character as an integer */ int getchar (void) ;
/* Input string into array s until newline */ char *gets (char *s) ;
/* To input a number of characters from a stream */ char *fgets (char *string1, int n, FILE stream) ; / where up to (n - 1) characters are accepted, including newline / / To output a string of characters to a stream */ char *fputs (char *string1, FILE stream) ; / where all the characters are placed into the I/O stream */
/* Passing an array to a function */ #include <stdio.h> #include <string.h> void mysub ( char [ ] ) ; int main ( ) { char name[20] = "Richard J. Freuler" ; mysub (name) ; return 0 ; }
void mysub ( char text[ ] )
{
int len, k ; len = strlen (text) ; printf ("%d\n", len ) ; for (k = 0 ; k < len ; k++) printf ("%c", text [k] ) ;
}
/*Program Output */
18
blanks
/* This program sorts strings using array of pointers */ #include <stdio.h> #include <string.h> #define SIZE 4 int main ( ) { int k, swaps ; char name[SIZE][30], *nptr[SIZE], *temp ; char filename[ ] = "namelist.dat" ; FILE *fptr ; fptr = fopen (filename,"r") ;
printf ("\n Original list\n") ;
for (k = 0 ; k < SIZE ; k++) /* Assign addresses / { / to pointers in array / nptr[k] = name[k] ; fgets (name[k], 30, fptr) ; printf ("%s", name[k]) ; / Print original list */ }
do /* Sort the pointers in ascending alphabetic / { / order of the strings */ swaps = 0 ; for (k = 0 ; k < (SIZE - 1) ; k++) { if (strcmp (nptr[k], nptr[k+1]) > 0) { temp = nptr[k] ; nptr[k] = nptr[k+1] ; nptr[k+1] = temp ; swaps=1 ; } } } while (swaps);
0 1 2 3 4 5 … 29 0 1 2 3
So, the name array would still look like:
And, the nptr array would end up as:
260 230 290 200
0 1 2 3
M I R A N D A \n
J A S O N \n
A N D Y \n
M E G A N \n \