1 / 24

C Programming

C Programming. Strings. Strings. Array of characters – most common type of array in C Let’s make them easier for use Denote the end of array using a special character We won’t need to indicate the length each and every time Easier initialization syntax. String Initialization.

howard
Download Presentation

C Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C Programming Strings

  2. Strings • Array of characters – most common type of array in C • Let’s make them easier for use • Denote the end of array using a special character • We won’t need to indicate the length each and every time • Easier initialization syntax

  3. String Initialization • Use a string instead of the usual braces and comma notation char str[] = "Text";char s[] = "Hello, World!";

  4. The array String Termination • Strings terminate with the special character '\0' (ascii code 0) • To hold a string of N characters we need an array of length (at least) N + 1 The string '\0' 's' 'H' 'H' '#' 'e' 'e' ' ' 'l' 'l' 'l' 'l' 'f' 'o' 'd' 'o' ' ' 'y' ' ' 'w' '4' 'w' 'o' 'o' '7' 'r' 'r' '$' '_' 'l' 'l' 'd' 'd' 'e' 'g' 'g' 'd' 'd' 'd' '.' '.' '.' 'p' 'p' 'p' Terminator

  5. String Initialization • Use a string instead of the usual braces and comma notation char str[] = "Text"; • Shorthand for the longer but equivalent char str[] = {'T', 'e', 'x', 't', '\0'};

  6. String Length int string_length(char str[]){int i = 0;while (str[i] != '\0') ++i;return i;}

  7. Printing Strings • We can use printfto print strings • Use %s to print from the string until '\0'

  8. Printing Strings int main(void) { char str[] = "Hello, World!"; printf("%s\n", str); str[5] = '\0'; printf("%s\n", str); str[10] = '#'; printf("%s\n", str); str[5] = ';'; printf("%s\n", str); return 0; } Hello, World! Hello Hello Hello; Wor#d!

  9. Reading Strings • getchar • read character by character • scanf • multiple character in a single read • will only read until the first space / newline • scanf("%s", str); NO ‘&’

  10. Example – Using getchar() #defineMAXLINE100 int main(void) { char str[MAXLINE + 1]; /* one more place for the '\0' */ char c; int i = 0; c = getchar(); while (c != '\n' && i < MAXLINE) { str[i] = c; ++i;c = getchar(); } str[i] = '\0'; /*Terminate the string */ printf("The string you entered is: %s\n", str); return 0; }

  11. Reading strings - scanf • scanf reads in letters until a space or newline ('\n') is encountered • The maximum length can be stated in the parentheses: • scanf("%10s", str); • read 10 characters and terminate with'\0' (str should be of size at least 11)

  12. Example – using scanf #define MAXLINE100 int main(void) { char str[MAXLINE + 1]; printf("Please enter a string:\n"); scanf("%100s", str); printf("The string you entered is: %s\n", str); return 0; } Input: fun and games with scanf output: The string you entered is: fun

  13. scanf problem • After using scanf the next character that will be read is the space or newline. • For example:scanf("%s", str);scanf("%c", &letter);Here letter has the value ‘ ’ or newline (‘\n’).

  14. Solving the problem • We need to read and discard the unwanted newline. • Either use getchar orinform scanf to expect spaces (also newline) before the next character.scanf("%s", str);scanf(" %c", &tav);

  15. Exercise • Implement the function:void replace(char str[], char from, char to); • The function replaces every occurrence of the first char with the second one. • Write a program to test the above function • read a string from the user (no spaces) and two characters • pass them as arguments to your function • print the result • Example • input: “papa” ‘p’ ‘m’ • output: “mama”

  16. Solution void replace(char str[], char from, char to) { int i; for (i = 0; str[i] != '\0'; ++i) { if (str[i] == from) str[i] = to; } }

  17. Solution #define MAX_STR_LEN 100 int main(void) { char str[MAX_STR_LEN + 1]; char from, to; printf("Please enter a string (no spaces)\n"); scanf("%100s", str); printf(“Character to replace: "); scanf(" %c", &from); printf(“Character to replace with: "); scanf(" %c", &to); replace(str, from, to); printf("The result: %s\n", str); return 0; }

  18. String library • Like in the case of stdio.h and math.h, we have a special library for handling strings • We should #include<string.h>

  19. String library • All functions assume that a string ends with ‘\0’. • Useful functions: • int strlen(char s[])returns the length of s • int strcmp(char cs[], char ct[])compares cs with ct • strcpy(char s[], char ct[])copies the contents of ct to s • strcat(char s[], char ct[])Concatenate ct to s • and more… see string.h library

  20. Exercise (1) • Implement the function void string_swap(char str1[], char str2[]); • The function accepts two strings and swaps them.

  21. Solution – string_swap void string_swap(char str1[], char str2[]) { int i = 0, temp, str1_len = strlen(str1), str2_len = strlen(str2); int max; if (str1_len > str2_len) max = str1_len; else max = str2_len; for (i = 0; i <= max; ++i) { temp = str1[i]; str1[i] = str2[i]; str2[i] = temp; } }

  22. Exercise (2) • Write a program that reads 10 words from the user and sort them. • Use a two-dimensional array to store the words • Use strcmpto compare two words • A word is a sequence of characters without spaces of length 20 or less

  23. Sort Reminder set n to number of words to be sortedrepeat for counter = 1 to n - 1 do   if key[counter] > key[counter+1] then     swap the words; end if end do  n = n - 1;until n = 1

  24. Solution - main int main(void) { char words[WORDS_NUM][WORD_SIZE + 1]; int i = 0, j = 0; /* read words from user */ for (i = WORDS_NUM; i >= 1; --i) { for (j = 0; j < i - 1; ++j) { if (strcmp(words[j], words[j + 1]) > 0) string_swap(words[j], words[j + 1]); } } /* print sorted words */ return 0; }

More Related