C Programming 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 Use a string instead of the usual braces and comma notation char str[] = "Text"; char s[] = "Hello, World!";
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 's''#'' 'f''d''y''4''7''$''_''e''g''d''.''p''H''e''l' 'o'' 'w''o''r''l''d''g''d''.''p''H''e''l' 'o'' 'w''o''r''l''d' '.''p' '\0' Terminator The array The string
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'};
String Length int string_length(char str[]) { int i = 0; while (str[i] != '\0') ++i; return i; }
Printing Strings We can use printf to print strings Use %s to print from the string until '\0'
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; Wor#d!
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 ‘&’
#define MAXLINE 100 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; } Example – Using getchar()
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)
Example – using scanf #define MAXLINE 100 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
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’).
Solving the problem We need to read and discard the unwanted newline. Either use getchar or inform scanf to expect spaces (also newline) before the next character. scanf("%s", str); scanf(" %c", &tav);
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”
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; }
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; }
String library Like in the case of stdio.h and math.h, we have a special library for handling strings We should #include
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 librarystring.h library
Exercise (1) Implement the function void string_swap(char str1[], char str2[]); The function accepts two strings and swaps them.
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; }
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 strcmp to compare two words A word is a sequence of characters without spaces of length 20 or less
Sort Reminder set n to number of words to be sorted repeat 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
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; }