New version page

Purdue CS 15900 - Chapter 11 Strings

Upgrade to remove ads

This preview shows page 1-2-3 out of 9 pages.

Save
View Full Document
Premium Document
Do you want full access? Go Premium and unlock all 9 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 9 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 9 pages.
Access to all documents
Download any document
Ad free experience

Upgrade to remove ads
Unformatted text preview:

Chapter 11StringsCS 159 - C ProgrammingString ConceptsString – a series of consecutive characters treated as a single unit.stringfixedwidthvariable widthlength controlleddelimitedString Concepts▪ Fixed-Length strings – remainder padded with spaced▪ Length-Controlled strings – length of string is stored ▪ Delimited strings – terminating character inserted at end* All of these implementation still reserve the exact same amount of memorychar name[9] = {'D','o','n',' ','H','o',' ',' ',' '};char name[9] = {'D','o','n',' ','H','o'};int nameLength = 6;char name[9] = {6,'D','o','n',' ','H','o'};char name[9] = {'D','o','n',' ','H','o','\0'};char name[9] = "Don Ho";String Conceptschar name[9] = "Don Ho";D o n H o \0\0\0Still part of the array,but not part of the stringString Concepts▪ A character literal is enclosed in single quotes▪ A string literal is enclosed in double quotes▪ 'x' is not the same as "x"▪ The empty string "" contains a terminating characterx x\0\0character 'x' string "x"empty string ""String Concepts▪ A string can be assigned when it is declared▪ But a string cannot be assigned like this laterchar name[10] = "Michael";char name[10];name = "Michael";String ConceptsA string still follows the rules of an ordinary array▪ Individual elements can still be accessed▪ They still they cannot be assigned all at oncechar name1[10];char name2[10];name1 = name2;char name[10] = "Don Ho";printf("The third character is \"%c\"",name[2]);The third character is "n"Program Example▪ What would be the output to this?char name[11] = "Javascript";name[4] = 0;printf("%s\n", name);name[4] = 's';printf("%s\n", name);String InputThe simplest approach is to use scanf using the %sconversion code (can also use with printf)▪ Notice that & is not used before the array variable in scanf because it already represents an address▪ You should always include a width modifier to ensure the bounds of the array are not exceeded▪ The scanf will only read data up until a newline or space character is entered and will replace it with the string termination characterchar name[SIZE];printf("Enter your name: ");scanf("%9s", name);printf("The name you entered was %s.\n", name);“5. Thou shalt check the array bounds of all strings..., for surely where thou typest "foo"someone someday shall type "supercalifragilisticexpialidocious".”– The Ten Commandments for C ProgrammersString InputTo accept a string with spaces, use the gets function in <stdio.h> instead▪ The gets function will absorb the newline character and automatically add the string terminator character▪ If the string exceeds the size of the array, you will get an error as it overwrites other parts of your program!char name[SIZE];printf("Enter your name: ");gets(name);printf("The name you entered was %s.\n", name);String InputTo accept a string with spaces and ensure that its size is not exceeded, use the getchar function in <stdio.h>char name[SIZE];printf("Enter your name: ");getString(name);printf("The name you entered was %s.\n", name);void getString(char str[]){int i = 0;dostr[i++] = getchar();while(i < SIZE && str[i - 1] != '\n');str[i - 1] = 0; // replace the '\n' with '\0'return;}String InputNumeric input is better handled by strings in order to prevent errors from a data-type mismatch (not required for course)#include <stdio.h> #include <stdlib.h> int main(void){char input[10];int num;printf ("Enter your number: ");scanf("%9s",input);num = atoi(input);printf ("You entered %d\n", num);return 0;}#include<stdio.h>#include<string.h>#include<ctype.h>#define SIZE 1000void getString(char x[]);void rot13(char[]);int main(void){char str[SIZE];printf("Enter a string: ");getString(str);rot13(str);printf("Encrypted string: %s\n", str);rot13(str);printf("Original string: %s\n", str);return 0;}void rot13(char str[]){int i;for(i = 0; i < strlen(str); i++){if(isalpha(str[i]))str[i] += toupper(str[i]) <= 'M' ? 13 : -13;}return;}Enter a string: The quick brown fox jumps over the lazy dogEncrypted string: Gur dhvpx oebja sbk whzcf bire gur ynml qbtOriginal string: The quick brown fox jumps over the lazy dogString Manipulation Functions▪ String copying▪ String length▪ String comparison▪ String concatenation<string.h>FunctionDescriptionintmemcmp(void *a, void *b, int n);Compare two memory blocksintstrcmp(char *a, char *b);Compare two stringsintstrncmp(char *a, char *b, int n);Compare characters of two stringschar* strcat(char *d, char *s);Concatenate two stringschar* strncat(char *d, char *s, int n);Concatentatecharacters from stringvoid* memcpy(void *d, void *s, int n);Copy memory blockvoid* memmove(void *d, void *s, int n);Move memory blockchar* strcpy(char *d, char *s);Copy stringchar* strncpy(char *d, char *s, int n);Copy characters from stringchar* strchr(char *d, int n);Search string for characterchar* strrchr(char *d, int n);Search string in reverse for characterchar* strpbrk(char *d, char *s);Search string for a set of characterssize_tstrspn(char *d, char *s);Search string for initial span of characters in setsize_tstrcspn(char *d, char *s);Search string for initial span of characters not in setchar* strstr(char *d, char *s);Search string for substringchar* strtok(char *d, char *t);Search string for tokensize_tstrlen(char *d);String lengthchar* strerror(int n);Convert error number to stringvoid* memset(void *ptr, int val,size_t n);Initialize memory block to specified valueString CopyingSince a string cannot be assigned to another string all at once (string1 = string2), it must be transferred one character at a timechar str1[SIZE];char str2[SIZE];int i = 0;printf("Enter a string: ");getString(str1);dostr2[i] = str1[i];while(str2[i++] != '\0');printf("The string you entered was %s\n", str2);String CopyingAlternatively, you could simply use the strcpy function from <string.h>char str1[SIZE];char str2[SIZE];int i = 0;printf("Enter a string: ");getString(str1);strcpy(str2, str1);printf("The string you entered was %s.\n", str2);String LengthThe string length can be determined by counting the number of characters (excluding the '\0' terminator)char str[SIZE];int i = 0;printf("Enter a string: ");getString(str);while(str[i] != '\0')i++;printf("The string length is %d\n", i);String LengthAlternatively, you could simply use the strlen function from <string.h>char str[SIZE];printf("Enter a string: ");getString(str); printf("The string length is %d\n", strlen(str));String ComparisonSince strings cannot be compared all at


View Full Document
Download Chapter 11 Strings
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Chapter 11 Strings and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Chapter 11 Strings 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?