cs 108 computing fundamentals march 26, 2015. class notes last day to withdraw from a class is...
TRANSCRIPT
CS 108 ComputingFundamentals
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 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 <stdio.h> // 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 <stdio.h> //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 <stdio.h> //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 );
StringsIn 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)
t sisih a s \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 <stdio.h> /* 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 <stdio.h> /* 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 <stdio.h> /* 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 variablechar 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 arraychar 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 <stdio.h> // 7a.c
#include <string.h>
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 <stdio.h> // 8a.c
#include <string.h>
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 <stdio.h> // 9a.c
#include <string.h>
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 <stdio.h> // 10a.c
#include <string.h>
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 <stdio.h> // 11a.c
#include <string.h>
int main(void)
{
char fake_fang_prompt [ ] = "urbanc@fang:~>" ;
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 <stdio.h> //12a.c
#include <string.h>
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 <stdio.h> // 13a.c
#include <ctype.h>
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 <stdio.h> //14a.c#include <ctype.h>
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 <stdio.h> //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 <stdio.h> //16a.c
#include <string.h>
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);
fgetschar * 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 <stdio.h> //17.c#include <string.h>
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 ) ;