Strings CSCI 112: Programming in C 1 String basics C stores - - PowerPoint PPT Presentation

strings
SMART_READER_LITE
LIVE PREVIEW

Strings CSCI 112: Programming in C 1 String basics C stores - - PowerPoint PPT Presentation

Strings CSCI 112: Programming in C 1 String basics C stores strings as arrays of char , terminated by the NULL character \0 The NULL character is used so that C knows where the end of the string is when it iterates over the array.


slide-1
SLIDE 1

1

Strings

CSCI 112: Programming in C

slide-2
SLIDE 2

2

String basics

2

  • C stores strings as arrays of char, terminated by the NULL

character \0

  • The NULL character is used so that C knows where the

end of the string is when it iterates over the array.

  • It is important to always include it when you manually build

string arrays, but C will automatically append it when you use most built-in string builders.

slide-3
SLIDE 3

3

Declaration & Instantiation

Declare a string as a simple array of characters This allocates space for a String up to 29 characters plus the NULL character.

3

slide-4
SLIDE 4

4

Declaration & Instantiation

Declare a string as a simple array of characters This allocates space for a String up to 29 characters plus the NULL character.

4

slide-5
SLIDE 5

5

Declaration & Instantiation

Instantiation can be done with a string literal: This string can hold up to 19 characters plus null character, but not all space is used:

5

slide-6
SLIDE 6

6

Arrays of String

An array of Strings is a 2D array—that is, an array of char arrays:

6

slide-7
SLIDE 7

7

Arrays of String

An array of Strings is a 2D array—that is, an array of char arrays: As with 2D arrays, the lengths of all but first dimension are required. Compiler needs to know how much space to allocate for each string, but can infer from literal how many strings there are.

7

slide-8
SLIDE 8

8

String I/O

The %s placeholder can be used in printf and scanf to denote the char array type: where string_var is a char array (or pointer to first element of char array)

8

slide-9
SLIDE 9

9

String I/O

The %s placeholder can be used in printf and scanf to denote the string type: where string_var is a char array (or pointer to first element of char array) C will print out the elements in string_var up to the \0 null character—this is why we need that at the end of strings!

9

slide-10
SLIDE 10

10

String I/O

The %s placeholder can be used in printf and scanf to denote the string type: where string_var is a char array (or pointer to first element of char array) C will print out the elements in string_var up to the \0 null character—this is why we need that at the end of strings! We can specify a minimum width, such as %#s (If string is less than # chars long, padding is added to left of string. Negative value of # will add padding to right of string.)

10

slide-11
SLIDE 11

11

String I/O

%s is used in scanf to take in string input from the console:

11

scanf("%s", char_array);

slide-12
SLIDE 12

12

String I/O

%s is used in scanf to take in string input from the console: Why is there no & before char_array?

12

scanf("%s", char_array);

slide-13
SLIDE 13

13

String I/O

%s is used in scanf to take in string input from the console: Why is there no & before char_array? Warning: a big pitfall of dealing with strings in C is overflow: what if the user enters a string that’s larger than char_array? We have to be careful of this, including when we start using some the C Library string functions

13

scanf("%s", char_array);

slide-14
SLIDE 14

14

String I/O

The scanf function will place characters of a string into the char array until it sees whitespace (or newline), at which point it adds the \0 null character into the array and stops.

14

slide-15
SLIDE 15

15

Example: Parallel arrays of strings

15

slide-16
SLIDE 16

16

C Library Functions and strings

Because strings are really arrays, a lot of the string manipulation we’re used to doing in other languages would be much harder in C if it weren’t for some built in library functions which handle the array manipulation for use. To use these functions, the string.h header file should be included. Page 463 of book gives a great table about some common string.h functions.

16

slide-17
SLIDE 17

17

C Library: Assignment

We can assign a string literal to a char array when we declare it, but we cannot reassign a value to it. (Since it’s an array, and the name of an array can’t go on the left-hand side of an assignment statement after declaration.)

17

char name[20] = "Fred"; name = "Greg";

slide-18
SLIDE 18

18

C Library: Assignment

The strncpy function copies a given number of characters from one char array (string) into another. The book talks about the strcpy (no n) function—be careful! It can cause an

  • verflow, overwriting your other variables or throwing a runtime error. It does not

limit the number of characters it will try to copy from one to the other.

18

slide-19
SLIDE 19

19

C Library: Assignment

The strncpy function copies a given number of characters from one char array (string) into another. If the source string is shorter than the max number of characters to copy, the remaining spaces (up to max) will be filled with \0 null characters.

19 Source string (does not have to be a literal, could be a char array) Destination string (must be a char array) Maximum number

  • f characters to

copy)

slide-20
SLIDE 20

20

C Library: Assignment

The strncpy function copies a given number of characters from one char array (string) into another. strncpy does NOT add the null terminator automatically, unless there’s remaining

  • space. We need to do this manually.

20 Source string (does not have to be a literal, could be a char array) Destination string (must be a char array) Maximum number

  • f characters to

copy)

slide-21
SLIDE 21

21

C Library: Assignment

21

slide-22
SLIDE 22

22

C Library: Substrings

The strncpy function can be sued to extract parts (substrings) of a string. Let’s say we want to get just the day from the string “January 30, 2005” How can we do this with strncpy, given the following setup? HINT: Remember that the first two arguments of strncpy take char pointers—they don’t have to be (though often are) the name of an array!

22 char date[17] = "January 30, 2005"; char day[3];

slide-23
SLIDE 23

23

C Library: Substrings

The strncpy function can be sued to extract parts (substrings) of a string. Let’s say we want to get just the day from the string “January 30, 2005” Notice that we have to manually add in the null character!

23 char date[17] = "January 30, 2005"; char day[3]; strncpy(day, &date[8], 2); day[2] = ‘\0’;

slide-24
SLIDE 24

24

C Library: Substrings

The strncpy function can be sued to extract parts (substrings) of a string. Let’s say we want to get just the day from the string “January 30, 2005” The first argument points to the first character in date, and the second to the 8th

  • character. (I.e., the “starting point” for the copy is the 8th character of day)

24 char date[16] = "January 30, 2005"; char day[3]; strncpy(day, &date[8], 2); day[2] = ‘\0’;

slide-25
SLIDE 25

25

Example: Break string into components

We want to take a string such as HeyThereImAString and print out its components separated by capital letter.

25

slide-26
SLIDE 26

26

C Library Functions: String length

Because strings are terminated by the \0 character, C can count the number of elements of the char array that make up a string, up until it sees that character.

26 string (Can be a literal, or pointer to a char array) Returns the size of the given string (size_t can be though of as an int)

size_t strlen(char *string)

slide-27
SLIDE 27

27

C Library Functions: Concatenation

Concatenation takes two strings and combines them to form a longer string. strncat appends the first n characters of the source string onto the end of the destination string.

27

char *strncat(char *destination, char *source, size_t n);

Source string (Can be a literal, or pointer to a char array) Destination string (must be a char array) Maximum number

  • f characters from

source to append to destination) Returns a pointer to destination string, now appended with source

slide-28
SLIDE 28

28

Retrieving a whole line of input: fgets

scanf can take in strings from the user, but it uses whitespaces as a delimiter. Sometimes, we want to include whitespace in our input strings. fgets (“get string from file”) takes in an entire line from the specified file. We can pass in stdin as the file, and it will pull from the console.

28

char *fgets(char *destination, size_t n, FILE *source)

Destination string (must be a char array) Pointer to input

  • FILE. (We can pass

stdin here and input will be read from console. Returns a pointer to destination string, now appended with source Maximum number

  • f characters to

place into destination

slide-29
SLIDE 29

29

String Comparison

We can’t check if one string comes before another alphabetically simply by writing string1 < string2…this would compare the pointers. Instead we use the strcmp function, which compares two strings, and returns an integer representing how they compare:

29 printf("str1 comes before str2 alphabetically \n");

slide-30
SLIDE 30

30

Building a formatted string: sprintf

sprintf is just like printf, but instead of outputting to the console, it outputs into a char array. This lets us build strings from a variety of data types.

30

int sprintf(char *target_string, "format", <values>);

Target char array (where the formatted string is written.) Returns an int specifying the number of characters written to target_string. Format string Same as printf Values (One per placeholder in format string, corresponding to type of placeholder)

slide-31
SLIDE 31

31

String type conversion: sscanf

sscanf is just like scanf, but instead of taking input from the console, it reads from a char array. This lets us convert (parts of) strings into other data types.

31

int sscanf(char *input_string, "format”, <values>);

Source char array (where C searches for the specified values.) Returns an int specifying the number of arguments successfully filled Format string Same as printf Destination (One per placeholder in format string, corresponding to type of placeholder)

slide-32
SLIDE 32

32

Operations on char: classification

32

slide-33
SLIDE 33

33

Operations on char: conversion

NOTE: For all of these char functions, you must include <ctype.h>

33

slide-34
SLIDE 34

34

Example: case-insensitive comparison

Since strcmp is based on the ASCII character codes, capital letters come before

  • lowercase. So, it would indicate that “Zoo” comes before “Apple”.

Let’s write a function which uses the char operations to perform a case-insensitive comparison.

34