C Characters and Strings

Similar documents
Chapter 8: Character & String. In this chapter, you ll learn about;

C: How to Program. Week /May/28

Characters and Strings

Chapter 8 - Characters and Strings

by Pearson Education, Inc. All Rights Reserved.

Chapter 8 C Characters and Strings

Introduction to string

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

C mini reference. 5 Binary numbers 12

LECTURE 15. String I/O and cstring library

Strings. Steven R. Bagley

Object Oriented Programming COP3330 / CGS5409

Scientific Programming in C V. Strings

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Chapter 9 Strings. With this array declaration: char s[10];

Computer Science & Engineering 150A Problem Solving Using Computers

Pointers, Arrays, and Strings. CS449 Spring 2016

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

Module: Safe Programming. Professor Trent Jaeger. CSE543 - Introduction to Computer and Network Security

8. Characters, Strings and Files

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio.

Computer Programming: Skills & Concepts (CP) Strings

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

1 Pointer Concepts. 1.1 Pointer Examples

N v 1. Type generic string interfaces honor the const contract of application code ISO/IEC JTC 1/SC 22/WG14. August 20, 2016

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

C Programming. Unit 9. Manipulating Strings File Processing.

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

Computer Programming

Arrays, Strings, & Pointers

ONE DIMENSIONAL ARRAYS

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

Overview. Concepts this lecture String constants Null-terminated array representation String library <strlib.h> String initializers Arrays of strings

Outline. Computer Programming. Structure of a function. Functions. Function prototype. Structure of a function. Functions

CMPSC 311- Introduction to Systems Programming Module: Strings

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Computers Programming Course 11. Iulian Năstac

Structured programming

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Lecture 05 Pointers ctd..

CS107 Spring 2019, Lecture 4 C Strings

Strings. Chuan-Ming Liu. Computer Science & Information Engineering National Taipei University of Technology Taiwan

Introduction to C/C++ Lecture 5 - String & its Manipulation

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

Intermediate Programming, Spring 2017*

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Chapter 8 Character Arrays and Strings

Chapter 5 - Pointers and Strings

C Libraries. Bart Childs Complementary to the text(s)

Chapter 5 - Pointers and Strings

CS107, Lecture 4 C Strings

Lecture 17. Strings II. CptS 121 Summer 2016 Armen Abnousi

CS106L Handout #05 Fall 2007 October 3, C Strings

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

LAB7 : Characters and Strings

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

CS24 Week 2 Lecture 1

Standard C Library Functions

Getting Started. Project 1

Course organization. Course introduction ( Week 1)

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

Fundamentals of Programming. Lecture 11: C Characters and Strings

C PROGRAMMING. Characters and Strings File Processing Exercise

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Fundamentals of Programming

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

CS 222: Pointers and Manual Memory Management

Fundamental of Programming (C)

Arrays, Strings, and Pointers

CSC 2400: Computer Systems. Arrays and Strings in C

Fundamentals of Programming & Procedural Programming

Arrays, Strings, and Pointers

C for C++ Programmers

a) (5 points) What is the output of the following code sequence? int *ptr = 0x1050; printf ("%x\n", ptr--); printf ("%x\n", ptr);

CSC 2400: Computer Systems. Arrays and Strings in C

Carnegie Mellon. C Boot Camp. June 15, Fernando Yinglan Zach Kevin

Arrays, Strings, and Pointers

CS 261 Fall Mike Lam, Professor. Structs and I/O

Arrays and Strings. CS449 Fall 2017

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Strings. Daily Puzzle

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

Contents. Preface. Introduction. Introduction to C Programming

Built-in Functions for NTCAs.

C Strings. Abdelghani Bellaachia, CSCI 1121 Page: 1

today cs3157-fall2002-sklar-lect05 1

K. N. King: chapters 8 and 12

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

ECE551 Midterm Version 1

CS 241 Data Organization Pointers and Arrays

Transcription:

CS 2060

Character handling The C Standard Library provides many functions for testing characters in ctype.h. int isdigit(int c); // is c a digit (0-9)? int isalpha(int c); // is c a letter? int isalnum(int c); // is c a digit or a letter? int isspace(int c); // is c a whitespace character? int islower(int c); // is c a lowercase letter? int isupper(int c); // is c an uppercase letter? int tolower(int c); // convert c to lowercase int toupper(int c); // convert c to uppercase

Character handling char string[] = "Hello, world!"; puts(string); { char *ptr = string; while ( *ptr ) { *ptr = toupper(*ptr); ptr++; } puts(string); } { char *ptr = string; while ( *ptr ) { *ptr = tolower(*ptr); ptr++; } puts(string); }

String conversion functions stdlib.h has functions to extract numbers from strings: double strtod( char *nptr, char **endptr ); // double long strtol( char *nptr, char **endptr ); // long The function sets *endptr to the location after the end of the number. char string[] = "10 ducks"; char *endptr; long num = strtol(string,&endptr); // num = 10 // endptr points to the third element of string. If you don t need endptr just pass NULL: long num = strtol(string,null);

Printing to a string We can use sprintf to format a string rather than printing to the console: int num_ducks = 10; char string[1024]; sprintf("%d ducks were found.",num_ducks); // string contains "10 ducks were found." Why is this method insecure?

Printing to a string sprintf might overflow the array, leading to a code vulnerability: int num_ducks = 10; char string[10]; sprintf(string,"%d ducks were found.",num_ducks); // string is not long enough -- overflow Instead we can use snprintf which includes the size of the string: int num_ducks = 10; char string[10]; snprintf(string,10,"%d ducks were found.",num_ducks); // string contains "10 ducks "

Reading from a string Similarly we can read values from a string using sscanf: char string[] = "10 ducks were found."; int num_ducks; char string2[1024]; sscanf(string,"%d %s",&num_ducks,string2); // num_ducks = 10, string2 = "ducks were found." Notice any vulnerabilties here?

Reading from a string Again it is safer to include the length of the string in the format specifier: char string[] = "10 ducks were found."; int num_ducks; char string2[6]; sscanf(string,"%d %5s",&num_ducks,string2); // num_ducks = 10, string2 = "ducks" Remember to leave room for the null terminator at the end of the string.

Copying a string We can copy strings using strcpy or strncpy: char *strcpy( char *to, const char *from ); char *strncpy( char *to, const char *from, size_t n ); Remember that the first argument is the destination and the second argument is the source this is typical in the C Standard Library.

Copying a string We can copy strings using strcpy or strncpy: char *strcpy( char *to, const char *from ); char *strncpy( char *to, const char *from, size_t n ); Remember that the first argument is the destination and the second argument is the source this is typical in the C Standard Library.

Concatenating strings We can concatenate strings using strcat or strncat: char *strcat( char *to, const char *from ); char *strncat( char *to, const char *from, size_t n ); The from string will be appended to the end of the to string. char result[1024]; char s1[] = "Hello"; char s2[] = ", "; char s3[] = "World!"; strcpy(result,s1); strcat(result,s2); strcat(result,s3); printf("%s\n",result);

Comparing strings We can compare strings using strcmp or strncmp: int strcmp( char *s1, const char *s2 ); int strncmp( char *s1, const char *s2, size_t n ); These functions return: 0 if the strings are equal a negative value if s1 < s2 a positive value if s1 > s2 Here < and > refer to phone book ordering: "Aardvark" < "Apple" < "Banana"

Comparing strings int red_count = 0, blue_count = 0, green_count = 0; char color[16]; printf("enter color: "); scanf(" %15s",color); if ( strcmp( color, "red" ) == 0 ) { red_count++; } else if ( strcmp( color, "blue" ) == 0 ) { blue_count++; } else if ( strcmp( color, "green" ) == 0 ) { green_count++; } puts("");

String search functions There are many string search functions available; we will discuss a couple here. char *strstr(const char *s1, const char *s2); strstr finds the first occurence of s2 in s1 and returns a pointer to the location in s1. If s2 is not found, the function returns NULL.

String search functions void printlocation( const char *string, const char *key ){ char *loc = strstr(string,key); if ( loc1!= NULL ) printf("%s found at index %d\n",key1,loc1-string); else printf("%s not found\n",key); } int main() { char string[] = "String to search"; char key1[] = "search"; char key2[] = "duck"; printlocation(string,key1); printlocation(string,key2); }

String tokenization The C Standard Library provides a tokenizer function strtotok: char *strtok( char *string, const char *separators ); The string is broken into tokens separated by any character in separators. The return value is a pointer to a string containing the next token. The second and later calls to strtok should pass NULL as the first argument. The function actually modifies string by inserting null terminators!

String tokenization char string[] = "Hello world, it s me the computer."; char separators[] = ",."; // tokenize string by space or punctuation // first call to strtok: pass string char *tokenptr = strtok(string, separators); while ( tokenptr!= NULL ) { printf( "%s\n", tokenptr ); // get next token: pass NULL tokenptr = strtok(null, separators); }

String length strlen finds the length of a string: size_t strlen( const char *str ); How does it calculate the length of the string?

Other string functions strlen finds the length of a string: size_t strlen( const char *str ); How does it calculate the length of the string? It searches for the null terminator, starting from the pointer.

Memory functions string.h also contains functions for manipulation of any kind of data. void *memcpy( void *to, void *from, size_t num_bytes ); memcpy copies num bytes bytes starting from from to to. What is the difference from strcpy?

Memory functions string.h also contains functions for manipulation of any kind of data. void *memcpy( void *to, void *from, size_t num_bytes ); memcpy copies num bytes bytes starting from from to to. It does not look for the null-terminator (instead, size of array is given). This is more efficient when the number of bytes to copied is known.

memcpy example #include <stdio.h> #include <string.h> int main() { char array1[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; char array2[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; memcpy( array1, array2, 5 ); } for ( int i = 0; i < 10; i++ ) printf("%d ",array1[i]); puts(""); What will this output?

memcpy example #include <stdio.h> #include <string.h> int main() { int array1[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int array2[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; // memcpy? } for ( int i = 0; i < 10; i++ ) printf("%d ",array1[i]); puts(""); How can we copy the first five integers from array2 to array1?

memcpy example #include <stdio.h> #include <string.h> int main() { int array1[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int array2[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; memcpy( array1, array2, 5*sizeof(int) ); } for ( int i = 0; i < 10; i++ ) printf("%d ",array1[i]); puts(""); Copy 5 (number of bytes in one integer).

memcpy example #include <stdio.h> #include <string.h> int main() { int array1[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // undefined behavior: memcpy( array1, array1+6, 6*sizeof(int) ); } for ( int i = 0; i < 10; i++ ) printf("%d ",array1[i]); puts(""); What is the issue here?

Memory functions memcpy causes undefined behavior when the two pieces of memory overlap. In this case we need to use memmove: void *memmove( void *to, void *from, size_t num_bytes ) memmove behaves as if we first copy from to a temporary block of memory, and then copy it to to. It is safe to use when the two blocks of memory overlap.

Memory functions memset sets an entire block of memory to the same (byte) value: void *memset( void *to, int value, size_t num_bytes ); value is converted to a char and then copied to num bytes starting from to.

memset example #include <stdio.h> #include <string.h> int main() { char str[] = "The password is secret"; } memset( str+16, *, 6 ); printf("%s\n",str); What will the output be?