Strings CSCI 112: Programming in C.

Slides:



Advertisements
Similar presentations
Strings Input/Output scanf and printf sscanf and sprintf gets and puts.
Advertisements

Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Strings CS240 Dick Steflik. What is a string A null terminated array of characters: char thisIsAString[10]; \0 The “\0” (null character)
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Chapter 9 Strings Instructor: Alkar / Demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Topic 10 - Strings.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
Introduction to C programming
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
CS 162 Introduction to Computer Science Chapter 17 C++ String Objects Herbert G. Mayer, PSU (Copied from Prof. Phillip Wong at PSU) Status 11/30/2014.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Chapter 8 Strings. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data structure using arrays of.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Introduction to Programming Using C Arrays. 2 Contents Arrays Subscripting.
Computer Organization and Design Pointers, Arrays and Strings in C
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Strings (Continued) Chapter 13
Characters and Strings
C Characters and Strings
Fundamentals of Characters and Strings
© 2016 Pearson Education, Ltd. All rights reserved.
Lecture 8 String 1. Concept of strings String and pointers
Chapter 7 Text Input/Output Objectives
Quiz 11/15/16 – C functions, arrays and strings
A First Book of ANSI C Fourth Edition
CSE 303 Lecture 14 Strings in C
Plan for the Day: I/O (beyond scanf and printf)
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
Arrays in C.
Programming in C Input / Output.
Computer Science 210 Computer Organization
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Object Oriented Programming COP3330 / CGS5409
Lecture 8b: Strings BJ Furman 15OCT2012.
C Stuff CS 2308.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Strings.
Week 9 – Lesson 1 Arrays – Character Strings
File Input and Output.
Beginning C for Engineers
C-strings In general, a string is a series of characters treated as a unit. Practically all string implementations treat a string as a variable-length.
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Chapter 16 Pointers and Arrays
Strings What is a string? It is an array of characters terminated with
Topics discussed in this section:
ECE 103 Engineering Programming Chapter 25 C Strings, Part 1
String manipulation string.h library
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C++ Programming Lecture 20 Strings
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C Characters and Strings
Week 5 - Wednesday CS222.
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

Strings CSCI 112: Programming in C

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

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.

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.

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:

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

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.

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)

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!

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.)

String I/O %s is used in scanf to take in string input from the console: scanf("%s", char_array);

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);

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);

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.

Example: Parallel arrays of strings

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.

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";

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.

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)

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)

C Library: Assignment

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];

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’;

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’;

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

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)

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)

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

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");

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)

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)

Operations on char: classification

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

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.