320 likes | 432 Views
EEE 243B Applied Computer Programming. 14 - Strings §11.1 – 11.3 Prof Sylvain P. Leblanc. Review. What do we mean by dereferencing a pointer? Given the following: int a = 8; int * p ; char b = 'v'; char* r; p =&a; Can we do the following: r = p ; * p =( int )b;
E N D
EEE 243BApplied Computer Programming 14 - Strings §11.1 – 11.3 Prof Sylvain P. Leblanc
Review • What do we mean by dereferencing a pointer? • Given the following: int a = 8; int* p; char b = 'v'; char* r; p=&a; • Can we do the following: r = p; *p=(int)b; • What is a derived type? Prof S.P. Leblanc
Outline • General Strings Treatment in C • Fixed Length Strings • Variable Length Strings with Arrays • Variable Length Strings with Pointers • The Delimiter Character • Some of the most useful Strings Functions in C • Output Formatting Prof S.P. Leblanc
1. General Strings Treatment • Until now we have treated strings superficially. • We understand that a string represents a named “thing” in the environment • We name things to abstract what they are • Most languages provide a specific data type for strings such as Pascal or Java • In C we use two derived types to store strings • Arrays • Pointers Prof S.P. Leblanc
1. General Strings Treatment • A string is a logical unit of storage derived from the physical storage char type • What is interesting in strings is that they should and do vary in length • Last name … not all the same length • Car brand • Color… • How do we select the correct derived type and the appropriate data structure? Prof S.P. Leblanc
1. Strings Taxonomy • In the big scope of things, strings come in two flavours: fixed and variable length Prof S.P. Leblanc
2. Fixed Length Strings • Fixed length – • Array of characters that always store the same number of characters char collegeNo[5]; //College Numbers have 5 //alphanumerical chars • Pointer to a fixed length literal char province1[] = "AB"; //3 char array char* province2 = "ON"; //Abbreviation of 2 char Prof S.P. Leblanc
3. Variable Length Strings - Arrays Variable length – • Array of characters with delimiter char lastName[30] = "\0"; //empty string … lastName[0] = 'L'; lastName[1] = 'e'; lastName[2] = 'b'; //…The rest of my name … lastName[6] = 'c'; lastName[7] = '\0'; //I am done Prof S.P. Leblanc
4. Variable Length Strings - Pointers • Variable length – • Pointer to a max size literal char* name = "Superfragelisticespialladotious\0"; //This is dangerous because you must find the //longest name that you will use or plan for it… // The \0 is not needed – automatically added by // compiler when using double quotes • This is (almost) identical to char name[] = "Superfragelisticespialladotious"; Prof S.P. Leblanc
5. The Delimiter Character • In both the variable size strings that we saw, we used the delimiter character \0 • \0 is used in C as a logical backstop to tell our functions that we have reached the end of the string. • We could have used any character in the character set. • ASCII provides for 128 characters • We could have used a space or the letter a • But the chosen character could not have been used inside a string • It can only be used to signify logical end of string Prof S.P. Leblanc
5. Effect of the Delimiter Character Prof S.P. Leblanc
5. Logical and Physical Storage • We say that a string is a logical derived type • There can be a difference between the logical storage of the string (delimited by /0) and the physical storage reserved for it Logical storage ending with \0 Physical storage ending of 11 char Prof S.P. Leblanc
6. Initializing Strings • Strings can be initialized the same way as other arrays: with size, without size or with a pointer • char str[9] = "Good Day"; • char str[9] = {'G', 'o', 'o', 'd', ' ', 'D', 'a', 'y'}; • char month[]= "January"; • char* pStr = "Good Day"; Prof S.P. Leblanc
7. Some useful functions for strings • Fromstdio.h • printf • gets • fgets • puts • fputs • Fromstring.h • strcpy • strcat • strncat • strlen • itoa Prof S.P. Leblanc
7a. Output Formatting • We can use scanf() to read strings from the keyboard and printf()to print them to the screen (standard output) • float x = 233.12; • printf("The tax is $%8.2f dollars this year.\n", x); • The tax is $233.12 dollars this year. • int y = 2010; • printf(("The tax is $%8.2f dollars in %d.\n", x, y); • The tax is $233.12 in 2010. Prof S.P. Leblanc
7a. Output Formatting • Here are the conversion specifications for scanf() and printf() Prof S.P. Leblanc
7a. Output Formatting • Here are the flags, sizes and conversion codes for printf() Prof S.P. Leblanc
printf() one char at a time Prof S.P. Leblanc
printf() on char at a time with pointer Figure 11-10 Prof S.P. Leblanc
String Input • The gets() and fgets() functions take a line (terminated by a new line) from the input stream and turns it into a null-terminated string Prof S.P. Leblanc
String Output • The puts() and fputs() functions take a null-terminated string from memory and write it to the display (or to a file) Prof S.P. Leblanc
Copying strings with strcpy() • Use strcpy() to copy one string into another • Beware of string lengths! Use strncpy() Prof S.P. Leblanc
Comparing strings with strcmp() • strcmp(s1, s2) compares two strings, one char at a time. • returns 0 if s1 == s2 • returns -1 if s1 < s2 • returns 1 if s1 > s2 Prof S.P. Leblanc
Combining strings with strcat() • We can concatenate strings with strcat() • We can specify the number of char to concatenate with strncat() Prof S.P. Leblanc
Finding the length of a string with strlen() • strlen()returns the number of characters in a string before the first \0 • sizeof() will return the number of characters allocated to the array • NOTE: sizeof and strlen will NOT be the same!! Prof S.P. Leblanc
strlen() #include <stdio.h> #include <stdlib.h> #include <strings.h> int main(int argc, char *argv[]) { char test[25] = "This is a test"; printf(“%s\n”,test); printf("strlen(): %d sizeof %d\n",strlen(test),sizeof(test)); getch(); return 0; } Prof S.P. Leblanc
Converting integers to strings with itoa() • printf(), scanf(), and sprintf() take huge amounts of memory! • For embedded systems (like the robot) small functions with less functionality are used • itoa(int value, char* outString, int radix) • converts integer value into a string of characters and puts the result in outString • The value can be converted into binary, decimal or hexadecimal as determined by radix Prof S.P. Leblanc
itoa • outString is a pointer in the function definition • When calling itoa(), outString must point to allocated memory { char* convertedInt; itoa(17,convertedInt,10); } // Error MEMORY No memory allocated { char convertedInt[10]; itoa(17,convertedInt,10); } OKAY Prof S.P. Leblanc
DANGER WILL ROBINSON! • None of the string functions check to see if you have enough memory allocated! • You can cause a Kernel Overwriteon the LEGO if you write to memory using an uninitialized or too short an string! • On Dev-C++ you will get a run-time error if you write beyond the end of the char array! • On Dev-C++ it is MUCH EASIER to debug strings and pointers!!! Prof S.P. Leblanc
There are a lot more string functions • In Forouzan in Appendix F • On the gnu website • http://www.gnu.org/software/libc/ • Do a search on your computer or on google for string functions • \0 is your friend and it works. • Check the string functions from the course web page and read the descriptions before the next lab period. Prof S.P. Leblanc
Quiz Time • What are the two different kinds of strings • Why do we say that strings are a logical derived type? • How is the logical storage achieved? • Give ‘C’ code to convert the value 127 into a string in decimal. Prof S.P. Leblanc
Next • Pointers and Functions Prof S.P. Leblanc