Download presentation
Presentation is loading. Please wait.
1
Strings CSCI 112: Programming in C
2
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. 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. Broad Problem Specific Problem Contributions Impact High reliability / fast and consistent performance / low operating costs Translate theoretical into practical Which cluster provides content / which particular server in the cluster / then retrieve from cache / content not cacheable / redundancy and leader selection
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.
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.
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:
6
Arrays of String An array of Strings is a 2D array—that is, an array of char arrays:
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.
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)
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!
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.)
11
String I/O %s is used in scanf to take in string input from the console: scanf("%s", char_array);
12
String I/O %s is used in scanf to take in string input from the console: Why is there no & before char_array? scanf("%s", char_array);
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 scanf("%s", char_array);
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.
15
Example: Parallel arrays of strings
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.
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.) char name[20] = "Fred"; name = "Greg";
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 overflow, 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.
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. Destination string (must be a char array) Source string (does not have to be a literal, could be a char array) Maximum number of characters to copy)
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. Destination string (must be a char array) Source string (does not have to be a literal, could be a char array) Maximum number of characters to copy)
21
C Library: Assignment
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! char date[17] = "January 30, 2005"; char day[3];
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! char date[17] = "January 30, 2005"; char day[3]; strncpy(day, &date[8], 2); day[2] = ‘\0’;
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) char date[16] = "January 30, 2005"; char day[3]; strncpy(day, &date[8], 2); day[2] = ‘\0’;
25
Example: Break string into components
We want to take a string such as HeyThereImAString and print out its components separated by capital letter.
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. size_t strlen(char *string) Returns the size of the given string (size_t can be though of as an int) string (Can be a literal, or pointer to a char array)
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. char *strncat(char *destination, char *source, size_t n); Returns a pointer to destination string, now appended with source Destination string (must be a char array) Source string (Can be a literal, or pointer to a char array) Maximum number of characters from source to append to destination)
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. char *fgets(char *destination, size_t n, FILE *source) Returns a pointer to destination string, now appended with source Pointer to input FILE. (We can pass stdin here and input will be read from console. Destination string (must be a char array) Maximum number of characters to place into destination
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: printf("str1 comes before str2 alphabetically \n");
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. int sprintf(char *target_string, "format", <values>); Returns an int specifying the number of characters written to target_string. Target char array (where the formatted string is written.) Format string Same as printf Values (One per placeholder in format string, corresponding to type of placeholder)
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. int sscanf(char *input_string, "format”, <values>); Returns an int specifying the number of arguments successfully filled Source char array (where C searches for the specified values.) Format string Same as printf Destination (One per placeholder in format string, corresponding to type of placeholder)
32
Operations on char: classification
33
Operations on char: conversion
NOTE: For all of these char functions, you must include <ctype.h>
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.