CS 108 Computing Fundamentals March 26, 2015. Class Notes Last day to withdraw from a class is Monday, April 6 Next week I sent e-mails to a small number.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Lecture 9: Character and String
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
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.
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.
C Strings. The char Data Type for Storing Characters The char data type can is used to declare a variable that can hold a single character. Examples:
Chapter 10.
1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
C Programming Day 2 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
CHAPTER 8 CHARACTER AND STRINGS
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Chapter 9 Formatted Input/Output Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
3. FORMATTED INPUT/OUTPUT. The printf Function The first argument in a call of printf is a string, which may contain both ordinary characters and conversion.
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.
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String.
Chapter 8: Character and String CMPD144: Programming 1.
(9-1) Strings I H&K Chapter 8 Instructor - Andrew S. O’Fallon CptS 121 (October 19, 2015) Washington State University.
Chapter 8 Strings. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data structure using arrays of.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
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.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Characters and Strings
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
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.
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
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.
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.
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.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
Dr. Sajib Datta  Ordering elements in some way  For numeric data, ascending order is the most common  Lots of techniques for sorting  These.
CS 108 Computing Fundamentals March 3, Let's Review The Homework.
Chapter 9 - Formatted Input/Output
Strings CSCI 112: Programming in C.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Strings (Continued) Chapter 13
Characters and Strings
CS 108 Computing Fundamentals November 2, 2017.
Strings A string is a sequence of characters treated as a group
Arrays in C.
CS111 Computer Programming
Chapter 9 - Formatted Input/Output
Presentation transcript:

CS 108 Computing Fundamentals March 26, 2015

Class Notes Last day to withdraw from a class is Monday, April 6 Next week I sent s to a small number of folks I think should consider withdrawing Let's start today's class by finishing "Array Boot Camp"

Fundamentals of Characters and Strings Characters in C consist of any printable or nonprintable character in the computer's character set including lowercase letters, uppercase letters, decimal digits, special characters and escape sequences. A character is usually stored in the computer as an 8-bits (1 byte) unsigned integer. The integer value stored for a character depends on the character set used by the computer on which the program is running.

There are two commonly used character sets: ­ ASCII (American Standard Code for Information Interchange) ­ EBCDIC (Extended Binary Coded Decimal Interchange Code) Fundamentals of Characters and Strings

There are two commonly used character sets: ­ ASCII (American Standard Code for Information Interchange) ­ EBCDIC (Extended Binary Coded Decimal Interchange Code) Fundamentals of Characters and Strings

Example: ASCII character #include // 1a.c int main(void) { char demo_A = 'A'; char demo_Z = 'Z'; char demo_a = 'a'; char demo_z = 'z'; printf("\n ASCII integer value for A is %d", demo_A ) ; printf("\n ASCII integer value for Z is %d", demo_Z ) ; printf("\n ASCII integer value for a is %d", demo_a ) ; printf("\n ASCII integer value for z is %d", demo_z ) ; printf("\n\n\n"); printf("\n 65 in ASCII represents %c", 65 ); printf("\n 90 in ASCII represents %c", 90 ); printf("\n 97 in ASCII represents %c", 97 ); printf("\n 122 in ASCII represents %c \n\n", 122 ); return 0 ; }

Example (continued) #include //2a.c int main(void) { char ch; printf("\n\nEnter a character: "); scanf("%c", &ch); if ( ch >= 'A' && ch <= 'Z' ) { printf("\nCapital letter.\n"); } return 0 ; } #include //3a.c int main(void) { char ch; printf("\n\nEnter a character: "); scanf("%c", &ch); if ( ch >= 65 && ch <= (65+26) ) { printf("\nCapital letter.\n"); } return 0 ; } equivalent to

Character Type: char In C, characters are indicated by single quotes: char input_char = 'P'; printf("input_char is %c\n", input_char );

Strings In C a string is really an array of characters that ends with a special character: the null character ( '\0' ) … we use double quotes: "this is a string" // " " means the \0 is added But you can't use an assignment operator to assign a string to a character array char demo[80]; demo = "this is a string"; // Unacceptable assignment

Strings A null ( '\0' ) character is placed to mark the end of each string String functions use '\0' to locate end of string (so you don't need to pass a string's length as argument to a string function) tsisihas\0gnirt

Fundamentals of Characters and Strings A string in C is an array of characters ending with the null character ( '\0' ). It is written inside a double quotation mark ( " " ) A string may be assigned (in a declaration) to either a char array or to a char pointer: char color[ ] = "green";

In C Strings are Character Arrays (logically) Strings in C, in a logical sense, are arrays of characters which terminate with a delimiter (\0 or ASCII NULL character). char str_1 [ ] = {'H', 'e', 'l', 'l', 'o', '\0'}; char str_2 [10] = {'\0'}; str_2 is a ten-element array that can hold a up to nine characters + \0 Strings in C need the delimeter to determine where the string ends (remember: the length of a string is dynamic… it isn't determined before runtime) It's the delimiter position (not the size of the array) that determines the length of the string

Accessing String Characters Like any array, the first element of a string in C is at index 0. The second is at index 1, and so on … char str_2 [10] ; str_2[0] = 'P'; str_2[1] = 'u'; str_2[2] = 'l'; str_2[3] = 'p'; str_2[4] = '\0'; str_2 now contains the string "Pulp" + \0 + 5 unused (at this time) "blanks"

String Literals String literals are given as a string inside double quotes. You've used string literals many times already printf("Enter an inter value:"); String literals are often used to initialize a string array/pointer variable char str_1[10] = "Roswell"; char str_1 [ ] = "Roswell"; Remember: the NULL is added automatically to the end (if there is space available)

Entering Strings with scanf ( ) Use %s format specifier: ­ %s scans up to but does not include next white space ­ %ns scans the next n characters or up to the next white space, whichever is first ­ You only need to provide the starting address of the string with %s Example: scanf ("%s", str_1); scanf ("%2s", str_1); No ampersand (&) necessary when inputting strings (%s) into character arrays! But you an use the & if you like.

#include /* 4a.c */ int main (void) { char str_1[ ] = "Barber"; int index = 0; printf(" \n The pointer variable str_1 holds the value: %p \n ", str_1 ) ; printf(" \n The pointer variable str_1 points to string: %s \n ", str_1) ; printf(" \n Using array notation, str_1 element 0 is at address: %p \n ", &str_1[0] ) ; printf(" \n Using char format specifier and *, str_1 points to: %c \n\n\n\n", *str_1) ; printf("\n Using character format specifier and *, str_1 ele 6 holds the value: %c \n", *(str_1 + 6) ) ; printf("\n Using character format specifier and array notation, str_1 ele 6 holds value: %c \n", str_1[6] ) ; printf("\n Using int format specifier, str_1 ele 6 holds the value: %d \n", *(str_1 +6) ) ; printf("\n Using int format specifier and array notation, str_1 ele 6 holds the value: %d \n\n\n\n", str_1[6] ) ; printf("\n Using char format specifier and *, str_1 element 2 holds the value: %c \n", *(str_1 + 2) ) ; printf("\n Using char format specifier and array notation, str_1 ele 2 holds value: %c \n", str_1[2] ) ; printf("\n Using int format specifier, str_1 element 2 holds the value: %d \n", *(str_1 + 2 ) ) ; printf("\n Using int format specifier and array notation, str_1 element 2 holds the value: %d \n\n\n\n", str_1[2] ) ; return (0) ; }

Reading and Printing a String #include /* 5a.c */ int main ( void ) { char name [ 15 ] = {'\0'}; printf( " \n Enter your first name: " ); scanf( " %s ", name); printf( " \n Your first name is: %s \n\n ", name); printf( " \n Enter your whole name: " ); scanf( " %s ", name); printf( " \n Your whole name is: %s \n\n ", name); return (0); }

Reading and Printing a String #include /* 6a.c … it's safer to limit the characters input*/ int main ( void ) { char name [ 15 ] = {'\0'}; printf( " \n Enter your first name: " ); scanf( " %14s ", name); printf( " \n Your first name is: %s \n\n ", name); printf( " \n Enter your whole name: " ); scanf( " %14s ", name); printf( " \n Your whole name is: %s \n\n ", name); return (0); }

Strings in C We can change parts of a string variable char str_1[6] = "hello"; str_1[3] = 'p'; /* str_1 now contains "helpo" */ str_1[4] = '\0'; /* str_1 now contains "help" */ We must retain the delimiter… by replacing str_1[5] in the original string with a character other than '\0', this makes a string that has no end, which means it is not a string (it is an array of characters) We must stay within limits of array char str_1[6] = "Hello"; /* this is fine */ char str_2[5] = "Hello"; /* this is not fine… no space for the \0)

Strings in C %s format specifier is used to read a string in a scanf( ) call ­ %s ignores all leading white space ­ %s reads all characters until next white space is found ­ %s stores \0 (NULL) after last character ­ %s reads into an array (no & necessary because an array is a pointer constant) Example: char str_1[15]; scanf("%s", str_1); Remember: too many characters for array causes problems

Strings in C Use a width value in with the format specifier to limit the number of characters read: char str_1[15]; scanf("%14s", str_1); Important Point: you always need one space for the \0 so the "effective" width is always one less than the size of the array Strings shorter than the field specification are read normally (as The Terminator might say, "no problemo")

Strings in C %s format specifier used to print a string in printf( ) call: ­ characters in a string printed until \0 encountered char str_1[15] = "Santa"; printf("%s", str_1); Output: Santa Use width value to print string with spaces: printf("%14s", str_1); Output: Santa Use - flag to print string as "left justified": printf("%-14s", str_1); Output: Santa

String Functions  Pretty straightforward  The text is pretty clear  Practice questions at the end of the chapter are useful  Play with your food  We'll cover a variety of these functions today

String Functions #1: strcpy #include // 7a.c #include int main(void) { char your_state[15] ; char my_state[15]; printf("What state are you from? "); gets( your_state ) ; my_state = your_state ; // this won't work… we'll get a compiler error printf("I am from %s and you are from %s, too!\n", my_state, your_state); return(0); }

String Functions #1 continued: strcpy #include // 8a.c #include int main(void) { char your_state[15] ; char my_state[15]; printf("\nWhat state are you from? "); gets( your_state ) ; // compiler will produce a warning… we will discuss this strcpy( my_state, your_state ) ; printf("\nI am from %s and you are from %s, too!\n\n", my_state, your_state ); return(0); }

String Functions #2: strcmp #include // 9a.c #include int main(void) { char magic_word[ ] = "goosfraba"; char guessed_word [ 25 ] ; int result; printf("Try to guess the magic word: "); gets( guessed_word ) ; result = strcmp( magic_word, guessed_word ) ; if(result == 0) puts("That's the correct word!"); else puts("Sorry, that is not the correct word!"); return(0); }

String Functions #3: strcasecmp #include // 10a.c #include int main(void) { char magic_word[ ] = "goosfraba"; char guessed_word [ 25 ] ; int result; printf("Try to guess the magic word:"); gets( guessed_word ) ; result = strcasecmp( magic_word, guessed_word ) ; if(result == 0) puts("That's the correct word!"); else puts("Sorry, that is not the correct word!"); return(0); }

String Functions #4: strcat #include // 11a.c #include int main(void) { char fake_fang_prompt [ ] = ; char snappy_retort [ ] = " I don't do " ; char user_input [100] ; char response [100] ; while (strcasecmp ( user_input, "quit" ) ) { printf("%s", fake_fang_prompt) ; scanf("%s", &user_input) ; strcpy( response, snappy_retort ) ; strcat( response, user_input ) ; puts(response) ; } printf("OK, just for you I'll quit.\n") ; return(0); }

String Functions #5: strlen #include //12a.c #include int main(void) { char user_input[100]; int size = 0, index = 0; printf("\n\nEnter a word: ") ; scanf("%s", user_input ); printf("%s backwards is ", user_input ); size = strlen(user_input) ; for( index = size - 1 ; index >= 0 ; index = index - 1) putchar( user_input [ index ] ) ; printf("\n\n") ; return(0); }

String Functions #6: isspace/isalpha #include // 13a.c #include int main() { char input[200]; int subscript = 0, spaces = 0, letters = 0 ; printf("Enter a sentence: "); gets(input); while( input [ subscript ] ) { if( isspace( input [ subscript ] ) ) spaces = spaces + 1 ; if( isalpha( input [ subscript ] ) ) letters = letters + 1 ; subscript = subscript + 1 ; } printf("Your sentence has %d spaces and %d letters.\n", spaces, letters); return(0); }

String Functions #7: toupper/tolower #include //14a.c #include int main(void) { char input[200]; int index = 0 ; char c ; printf("Enter a sentence: "); gets(input); do { input[index] = toupper( input[index] ) ; index = index + 1; } while(input[index]); puts(input); return(0); }

Playing with String #include //15a.c int main(void) /* a program that counts the number of characters in a string */ { char sentence[ ] = "I love SUNY Poly."; int i, count = 0; for ( i = 0 ; sentence[i] != '\0' ; i++ ) { count++; } printf(" %s: %d characters including the whitespace.\n\n", sentence, count); return 0 ; }

Arrays of Strings (1) Since strings are arrays themselves, using an array of strings can be a little tricky An initialized array of string constants char months[ ][ 10 ] = { "Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec" }; int m; for ( m = 0; m < 12; m++ ) printf( "%s\n", months[ m ] );

Arrays of Strings (2) An array of 12 strings each 20 chars long (remember that we need space for the \0) char names[ 12 ] [ 21 ]; int n; for( n = 0; n < 12; ++n ) { printf( "Please enter your name: " ); scanf( "%20s", names[ n ] ); }

scanf and Strings scanf( ) reads up to the first white space… it ignores the anything typed in after that. Be careful using it. char demo[10]; printf("Enter a string: "); scanf("%9s", demo); // Remember: no & necessary printf("You entered %s\n\n", demo)

scanf and Strings: Safer Approach 1 Use %widths to copy only up to some number number of characters. char demo[10]; printf("Enter a string: "); scanf("%9s", demo); printf("You entered %s\n\n", demo)

scanf and Strings: Safer Approach 2 #include //16a.c #include int main(void) { char user_input[11]; int size = 0, index = 0; printf("\n\nEnter a word: ") ; scanf("%10s", user_input ); printf("%s backwards is ", user_input ); size = strlen(user_input) ; for( index = size - 1 ; index >= 0 ; index = index - 1) putchar( user_input [ index ] ) ; printf("\n\n") ; return(0); }

getchar getchar ( ) will fetch one (1) character from the input stream char demo ; printf("Enter a character: "); demo = getchar( ); printf("You entered %c \n\n", demo);

fgets char * fgets( charArray, lengthLimit, file_pointer of stdin ) fetches a whole line, up to the size limit or when it reads a new line character '\0' added at the end of string Example: char demo[80]; fgets( demo, 79, stdin ) ; // fetch from keyboard Returns a NULL if something went wrong, otherwise a pointer to the array

#include //17.c #include int main(void) { char user_input[100]; int size = 0, index = 0; printf("\n\nEnter a word: ") ; fgets(user_input, 99, stdin ); printf("%s backwards is ", user_input ); size = strlen(user_input) ; for( index = size - 1 ; index >= 0 ; index = index - 1) putchar( user_input [ index ] ) ; printf("\n\n") ; return(0); }

String Copy Thoughts (strcpy) Consider this: char your_state[15] = "Alaska" ; char my_state[7]; printf("What state are you from? "); fgets( your_state, 14, stdin) ; strcpy( my_state, your_state ) ; There is no error checking! ­ If the destination array is shorter than source array, strange things could happen… no compile errors and often no runtime errors… could be a source of a security breach

Safer Approach: strncpy Copies at most N characters from source to destination (or up to '\0') If length of the source is greater than N, it copies only the first N characters If length of the source is less than N, it pads the remaining elements in destination with '\0'

strncpy in Action Consider this: char your_state[15] = "Alaska" ; char my_state[7]; printf("What state are you from? "); fgets( your_state, 14, stdin) ; strncpy( my_state, your_state, 7 ) ;