Presentation is loading. Please wait.

Presentation is loading. Please wait.

String manipulation string.h library

Similar presentations


Presentation on theme: "String manipulation string.h library"— Presentation transcript:

1 String manipulation string.h library

2 Homework Read through the supporting materials for next week
Try accepting command line arguments and answer the questions: Explain the semantics for the first dimension of argv. How long is the first dimension length for argv? Explain the semantics for the second dimension of argv. How long is the second dimension length for argv? Explain the following argc values: 1, 2, 3, … 2018 Risto Heinsar

3 String String is just an array of characters
Strings are between quotation marks, characters between apostrophes C strings are zero-terminated ('\0') char w[] = "Icecream" char w[12] = "Icecream" C uses 8-bit ASCII (every character is actually a number) 'A' – 65, 'B' – 66, 'C' – 67 'a' – 97, 'b' – 98, 'b' – 99 '0' – 48, '1' – 49, '2' – 50 '\t' – 9, '\n’ – 10 I c e r a m \0 I c e r a m \0 2018 Risto Heinsar

4 Reading strings char arr[10]; Create an array for 10 characters (9 usable + zero-terminator) gets(arr); Reads from the keyboard until newline, not recommended in production, deprecated (buffer overflow) fgets(arr, 10, stdin); Reads from a file (stdin – using keyboard input stream instead of file), newline character is also saved! scanf("%9s", arr); Reads until newline or 9 characters scanf("%[^\n]%*c", arr); Reads until newline, allows for buffer overflow attack getchar() ja fgetc() Reads a single character, typically used in a loop, more complicated but useful 2018 Risto Heinsar

5 Manipulating strings We can assign and compare characters conventionally word[0] == 'a'; word[0] = 'a'; We cannot do the same with strings (arrays) word = "Icecream"; word == "Icecream"; To help us manipulate strings, we can use <string.h> library 2018 Risto Heinsar

6 Sample 1: treating string as an array
#include <stdio.h> int main(void) { int i = 0; char word[] = "Icecream"; printf("Printing as a string: %s\n", word); printf("Printing one character at a time on separate lines:\n"); while (word[i] != '\0') printf("%c\n", word[i]); i++; } return 0; 2018 Risto Heinsar

7 strlen() – string length
Find the length of a string strlen(myStr); myString – the string to find the length of. Null-terminator is not counted. Returns the length of the string as an integer >>> Write a code snippet where you ask for the user for a sentence and the program outputs its length. 2018 Risto Heinsar

8 Sample 2: using string.h #include <stdio.h> #include <string.h> int main(void) { int i, n; char word[] = "Icecream"; for (i = 0, n = strlen(word); i < n; i++) // printf("%c", word[i]) – this is considered wasteful putchar(word[i]); } putchar('\n'); return 0; 2018 Risto Heinsar

9 Sample 3 #include <stdio.h> #include <string.h> int main(void) { int i, n; char word[] = "Icecream"; for (i = 0, n = strlen(word); i < n; i++) if (word[i] == 'e') printf("Letter 'e' found in position %d\n", i + 1); } putchar('\n'); return 0; 2018 Risto Heinsar

10 strstr() – substring, string in string
Finds if one string contains another string (substring) strstr(str1, str2); str1 – string where to search from str2 – string to search for (substring, the key) A NULL is returned, if the substring is not found a nonzero value is returned, if the substring is found It’s the location of the first matching character (memory address) >>> Improve your program so that the user can search for a word in the previously entered sentence. Found / not found is sufficient. 2018 Risto Heinsar

11 strcmp() – string compare
Compares 2 strings. The comparison is done one character. The characters are compared from first until the end is reached or a discrepancy is found. strcmp(str1, str2); str1 ja str2 are the strings to be compared 0 is returned, if the strings are identical A negative integer is returned, when str2[i] character is of a smaller value than str1[i] A positive integer is returned, when str2[i] character is of a greater value than str2[i] >>> Change your existing code so that it can’t be executed before the user has entered a the correct password. 2018 Risto Heinsar

12 strcat() – string concatenate
Concatenates a copy of the source to the destination string. The original string is preserved, concatenation starts from the old string’s terminating character ('\0'). destString’s size must be big enough to hold the concatenated string. E.g. If the strings are 4 and 6 characters, the destination must be 11+ strcat(destString, sourceString); destString – the target string sourceString – the string that will be concatenated onto another return – the location of the destString in memory 2018 Risto Heinsar

13 strcpy() – string copy Copies a string to a new location, the source is preserved. The string that’s currently at the destination will be overwritten. destString’s size must be sufficient to store the copied string. strcpy(destString, sourceString); destString – the location of the string where the copy will be stored sourceString – string that will be copied return – the location of the destString 2018 Risto Heinsar

14 strcpy() and strcat() Add a code snippet that will ask the user for their first and last name The result must be stored in a new character array You can try to use strcpy and strcat or look for other useful functions from string.h and sample code on character assignments Use the following format: "Last_name_initial. Firstname" e.g."Smith", "John" -> "S. John" >>> Got all this in one file? This was lab task #1 2018 Risto Heinsar

15 End result of lab task #1 User is asked for the password, the program does not proceed before the correct password is entered User enters a sentence, show how many characters it contained User is asked for a search word, print whether it was present in the entered previous sentence or not User is asked for first and last name. Create a short form from them. The latter must be combined into a new (empty) char array, original variables should be left untouched Create at least 2 additional meaningful functions! 2018 Risto Heinsar

16 Lab task #2 (use basecode)
Create a program, that generates addresses for people based on their first and last names The names are given in a simplified CSV format – first and last name are separated by a comma. It is given in an initialized string array. Use 3 characters from first and last name Maria,Kask -> Hints: to get lower case characters, look into ctype.h library or use ASCII + some math You can just print the required parts, no need to form a new array 2018 Risto Heinsar

17 Advanced for lab task #1 Make the search case insensitive
Don’t count punctuation marks, spaces, numbers into the length of the sentence (only a-z, A-Z) Create a multiuser authentication system with personal welcome messages and passwords E.g. Asks for a username and a password and then verifies it. If it matches, message is printed and the program continues 2018 Risto Heinsar

18 Advanced for lab task #2 Make it work for people with shorter names
Add another CSV field for phone number, print it out as a listing. E.g. name: Maria Kask phone: Make it possible for the field itself to have a comma 2018 Risto Heinsar


Download ppt "String manipulation string.h library"

Similar presentations


Ads by Google