Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 11: Strings B Burlingame 11 April 2018.

Similar presentations


Presentation on theme: "Lecture 11: Strings B Burlingame 11 April 2018."— Presentation transcript:

1 Lecture 11: Strings B Burlingame 11 April 2018

2 Announcements Midterm due Read chapter 9 Homework #7 due next week
Sign up for review sessions over the next week Read chapter 9 Homework #7 due next week

3 Plan for today Review strings
Demonstrate an approach to solving Happy Numbers

4 Recall: What is an Array?
So far we've dealt with scalar variables contain just one value Arrays are collections of data of the same type that occupy contiguous memory locations Individual values in the collection are called elements of the array Need to declare before use: #include <stdio.h> int main() { int i=0; double test[4] = {0}; test[0]=95.5; test[1]=74.0; test[2]=88.5; test[3]=91.0; for(i=0; i<4; i++) printf("test[%d]=%lf",i,test[i]); 0x%p\n",&test[i]); } return 0; Run array_practice2.c in ChIDE. Format (1D array) type array_name [num_elements]; Ex. Array of 4 doubles named, 'test'

5 Strings Strings are encoded arrays of characters designed to hold language Recall that all characters are encoded as numeric values Most modern systems use a variant of ASCII or Unicode We’ll assume ASCII

6 Strings By convention, strings in C are a null terminated array of characters There is no intrinsic string datatype Null equals character value 0 i.e. char z = 0; z has a null character written \0 Declaration: char string[] = “Hello world”; Stored: Hello World\0 (ie 12 characters) All string handling expects this

7 Working with strings Much like working with pointers and arrays
Many helper routines in string.h strcmp – tests strings for equivalence strcat – concatenates two strings strstr – locates a string within a string Etc. char string[] = “Hello World”; for( int i = 0; string[i] != 0 ; ++i ) { if( string[i] >= ‘A’ && string[i] <= ‘Z’ ) string[i] = string[i] + (97 – 65); }

8 Comparing strings #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { char name[100] = "Falken"; // String literal initialization char input_name[100] = ""; // Empty string initialization char buff[100] = { 0 }; // All null initialization fgets(buff, sizeof(input_name), stdin); sscanf(buff, "%s", input_name); // Note the lack of & if (strcmp(input_name, name) == 0) // strcmp is in string.h, unusually { // strcmp returns <0, 0, or >0. // 0 means "no difference" printf("Hello Professor %s\n", input_name); } else printf("Hello %s, would you like to play a game?\n", input_name); return(EXIT_SUCCESS);

9 References Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York, p. 327. Visited 23OCT2010.


Download ppt "Lecture 11: Strings B Burlingame 11 April 2018."

Similar presentations


Ads by Google