23
1 Lecture 28-29: Strings 2-3 APS106 (L.H. Shu) Outline: Examples of user-defined functions to: print strings copy strings compare strings Character and string handling library functions

Prograham.Pptx

Embed Size (px)

Citation preview

1

Lecture 28-29: Strings 2-3���APS106 (L.H. Shu)������ Outline: •  Examples of user-defined functions to:

print strings copy strings compare strings

•  Character and string handling library functions

2

Summary of strings 1 lecture •  string = series of chars that end with ‘\0’ •  pointer to string constant

char *sptr = “Hi”; –  non constant pointer that points to const data

•  string variable = array of chars ending with ‘\0’ that can be modified char s[] = “Hi”;

–  const pointer pointing to non constant data •  string input functions do not check whether

sufficient space is allocated for entry

3

/*write function to print string one char at time */ #include <stdio.h> void printCharacters(const char *); void main(void) { char string[ ] = “hi”; printCharacters(string); putchar('\n'); } /* Note: function printCharacters –

–  returns nothing, –  takes as argument non-const pointer (can change) to constant data

(not to be changed) –  data const to protect from accidental change (just want to print) */

4

void printCharacters(const char *s) { for (; *s!= '\0'; s++) putchar(*s); } •  for loop:

–  no initialization –  continuation condition: as long what s points to

is not null terminator –  data modification, increment s by one –  body: print to screen the char s points to

•  putchar, like puts (put string) except for chars;

/* Function definition */

5

/* print string one char at time w/ non-const ptr to const data */ #include <stdio.h> void printCharacters(const char *); void main(void) { char string[ ] = “hi”; printCharacters(string); putchar('\n'); } void printCharacters(const char *s) { for (; *s!= '\0'; s++) putchar(*s); }

output: hi

6

/* Copy string using array notation and pointer notation */ #include <stdio.h> void copy1(char *, const char *); void copy2(char *, const char *); void main(void) { char string1[10], *string2 = "Hi", string3[10], string4[]= "Ho"; copy1(string1, string2); printf("string1 = %s\n", string1); copy2(string3, string4); printf("string3 = %s\n", string3); }

7

void copy1(char *s1, const char *s2){ int i; for (i=0; s1[i]=s2[i]; i++) ; /* do nothing in body */ } /* Notes: - ‘to’ string not const, ‘from’ string data const - using array index notation on pointers

–  copying is done in continuation test –  data modification: increment array index */

/* copy s2 to s1 using array notation */

8

void copy2(char *s1, const char *s2){ for (; *s1=*s2; s1++, s2++) ; /* do nothing in body */ } /* Notes: ‘to’ string not const, ‘from’ string data const - loop using pointer notation

–  no initialization –  copying is done in continuation test –  data modification: increment both ‘to’ and ‘from’ pointers to point to next char */

/* copy s2 to s1 using pointer notation */

9

/* Copy string using array notation and pointer notation */ #include <stdio.h> void copy1(char *, const char *); void copy2(char *, const char *); void main(void) { char string1[10], *string2 = "Hi", string3[10], string4[]= "Ho"; copy1(string1, string2); printf("string1 = %s\n", string1); copy2(string3, string4); printf("string3 = %s\n", string3); } •  Output:

string1 = Hi string3 = Ho

10

/* Program to compare two strings */ #include <stdio.h> int str_compare(const char *, const char *); void main(void) { char *string1 = "Hi", *string2 = "Hi!"; printf("\"%s\" and \"%s\" are ", string1, string2); if (!str_compare(string1, string2)) printf("identical\n"); else printf("different\n"); }

11

int str_compare(const char *s1, const char *s2) { for (; *s1 == *s2; s1++, s2++) if (*s1 == '\0') return 0; /* strings are the same */ return 1; /* strings are different */ } /* Notes: strings being compared, both contents protected by const •  pointers not const - pointer incrementation used to move thru string •  for loop

–  condition: continue while what both pointers point to are same. –  loop body: if reached end of one string (‘\0’) - strings are same –  data modification: increment both pointers to next char

•  if for loop exited w/o reaching end of string, then * s1 == * s2 was at some point not true, therefore, strings not equal. */

12

/* Program to compare two strings */ #include <stdio.h> int str_compare(const char *, const char *); void main(void) { char *string1 = "Hi”, *string2 = "Hi!"; printf("\"%s\" and \"%s\" are ", string1, string2); if (!str_compare(string1, string2)) printf("identical\n"); else printf("different\n"); } Output:

Hi and Hi! are different

13

Summary so far •  string print/compare/copy functions rely on

the presence of ‘\0’ to work •  2 types of const or not with pointers:

const datatype *const pointer_name; –  const used to protect data that should not be

overwritten –  pointers that are incremented cannot be const

•  strings that are written into (copy to) need to have sufficient memory allocated

14

Recall... •  In memory,

–  characters are stored as one-byte ints –  one-byte ints stored as binary #’s

e.g., using lookup table to find ASCII equiv of char ‘a’ = 97 = 0110 0001

–  character constant = ASCII char in single quotes, e.g., ‘a’

15

char i/o functions •  prototyped in stdio.h •  already seen

int putchar(int c) /* print single character */ •  reverse is: int getchar(void)

int i; i = getchar(); printf(“i = %c”, i); printf(“i= %d”, i);

•  if user enters ‘b’, output: i = b i = 98

16

char handling functions •  13 lib functions for single chars •  ctype.h contains prototypes for functions •  functions receive char (rep as int) as argument •  functions return int •  is .. functions – check if passed char is ... e..g, int isdigit (int c)

•  to... functions, convert passed char to e.g., upper/lower case e.g., int tolower(int c)

17

char handling library functions

18

Using char handling functions char c; scanf(“%c”, &c); if (isdigit(c)) printf(“%c is a digit,” c); printf(“upper case of ‘a’ is %c”,

toupper(‘a’)); output:if user enters 2

2 is a digit upper case of ‘a’ is A

19

Strings containing numbers not the same as numbers •  e.g., string constant “2593” is not stored as 2 5 9 3

in discrete spaces

•  int 2593 stored as 0 1 0 1 0010 0001 2048 512 32 1

“2593” stored as ‘2’ ‘5’ ‘9’ ‘3’ ‘\0’ discrete ints 2, 5, 9, 3char ascii bin rep 2 = 0000 0010‘2’ 50 0011 0010 5 = 0000 0101‘5’ 53 0011 0101 9 = 0000 1001‘9’ 57 0011 1001 3 = 000 0011‘3’ 51 0011 0011‘\0’ 0 0000 0000

20

string conversion functions •  prototyped in <stdlib.h> •  converts strings that contain numerical chars to actual

numbers e.g., int atoi (const char *nptr);

char nums[] = “2593”; int i; i = atoi(nums); printf(“%d\n”, i –593); Can also send literal string to functions expecting ptr to

char, e.g., i = atoi(“2593”);

output: 2000

21

string manipulation and comparison •  e.g., strcat in string.h

char str1[20] = “hi ”; char str2[20]= “ho”; printf(“%s”, strcat(str1, str2); output:

hi ho

22

string searching functions •  prototyped in string.h char *strchr(const char *s, int c); /* returns pointer to 1st occurrence of c in s */ char *ptr; char string[] = “abcde”; char ch = ‘d’; if ( (ptr = strchr(string, ch)) != NULL) printf(“char %c appeared %d spaces away from 1st letter \n”, ch,(ptr-string)/sizeof(char));

Output:

char d appeared 3 spaces away from 1st letter

23

String i/o functions char *gets(char *s);

–  enters chars from stdin until \n or EOF, adds \0. –  also returns address of 1st byte pointed to by s

•  diff b/w gets & scanf –  scanf stops at white space –  gets stops at \n

•  sprintf – output directed to array of chars char sentence[80]; sprintf(sentence, “These chars are written into sentence, can also have format specs”);