Lecture 19: Working with strings
What Is a String? Importance Used in developing editors, word processors, page layout software, any kinds of text-processing software Strings Series of characters treated as a single unit. Can include letters, digits and various special characters such as +, -, *, /, $, \t, \n. String literal (string constant) in C are written in double quotation marks. “Hello EPSII” In C, a string is an array of characters ending in the null character (‘\0’).
Definition and Initialization Similar to the array definition; The data type of the elements is char. Strings are represented as character arrays ending with '\0' Strintgs char str[ ] = “hello”; char str[ ] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}; Arrays int aryInt[ ] = {1, 2, 3, 4, 5}; char aryChar[ ] = {‘h’, ‘e’, ‘l’, ‘l’, ’o’}; Strintgs (#define SIZE 10) char str[SIZE] = “hello”; SIZE > length(“hello”) Arrays (#define SIZE 10) int aryInt[SIZE] = {1, 2, 3, 4, 5}; char aryChar[SIZE] = {‘E’, ‘P’, ‘S’}; The value of a string is the address of its first character. A string is a pointer to the string’s first character. An array is also a constant pointer to its first element.
Definition and Initialization A string can be defined as a variable of type char * const char *colorPtr = “blue”; Create a pointer variable colorPtr that points to the string “blue” somewhere in memory. Inputting strings Using scanf scanf(“%s”, word); Copies input into word[ ] Do not need & (a string evaluates the address of its first character) Remember to leave room in the array for ‘\0’ char word[20]; scanf(“%19s”, word); scanf reads up to 19 characters
Standard Input/Output Library Functions Functions in <stdio.h> Used to manipulate character and string data
Standard Input/Output Library Functions
String Manipulation Functions of the String Handling Library Functions in <string.h> String handling library has functions to Manipulate string data Search strings Tokenize strings Determine string length
String Manipulation Functions of the String Handling Library
String Manipulation Functions of the String Handling Library
Practice Question Q. What is NOT the right way to create a character array and assign it the string “I love EPS II”? char string[25]= “I love EPS II”; char string[25]; strcpy(string, “I love EPS II”; string = “I love EPS II”; char string[25] = {‘I’, ‘ ‘, ‘l’, ‘o’, ‘v’, ‘e’, ‘ ‘, ‘E’, ‘P’, ‘S’, ‘ ‘, ‘I’, ‘I’, ‘\0’}; sprintf(string, “%s”, “I love EPS II”); Solution: C