Download presentation
1
Strings Chapter 13
2
13.1 String Literal (字串) A string literal is a sequence of characters enclosed within double quotes: "When you come to a fork in the road, take it." String literals may contain escape sequences. For example "Candy\nIs dandy\nBut liquor\nIs quicker.\n --Ogden Nash\n" Candy Is dandy But liquor Is quicker. --Ogden Nash
3
Continuing a String Literal
The backslash character (\) can be used to continue a string literal from one line to the next: printf("When you come to a fork in the \ road, take it. --Yogi Berra"); When two or more string literals are adjacent, the compiler will join them into a single string: printf("When you come to a fork in the " "road, take it. --Yogi Berra");
4
To Store a String Literal
C treats string literals as character arrays. The array contains a series of characters with '\0' (null character) at the end. "It is 3.6%." Null character Space symbol
5
To Store a String Literal
String literals can be empty. ("") Null character
6
I/O with String Literals
Both printf and scanf expect a value of type char * as their first argument. The following call of printf passes the address of "abc" (a pointer to where the letter a is stored in memory): printf("abc");
7
Operations on String Literals
We can use a string literal wherever C allows a char * pointer: char *p; p = "abc"; This assignment makes p point to the first character of the string. p
8
Operations on String Literals
String literals can be subscripted: char ch; ch = "abc"[1]; The new value of ch will be the letter b. A function that converts a number between 0 and 15 into the equivalent hex digit: char digit_to_hex_char(int digit) { return " ABCDEF"[digit]; }
9
Operations on String Literals
Attempting to modify a string literal causes undefined behavior: char *p = "abc"; *p = 'd'; /*** WRONG ***/ A program that tries to change a string literal may crash or behave erratically.
10
String Literals vs. Character Constants
A string literal containing a single character isn’t the same as a character constant. "a" is represented by a pointer. 'a' is represented by a character. A legal call of printf: printf("\n"); An illegal call: printf('\n'); /*** WRONG ***/
11
13.2 String Variables Any one-dimensional array of characters can be used to store a string. Storing "Tom Hanks" in char k[12] Therefore, please define an array which size is larger than the string stored in it by at least 1 byte! (for the null character '\0' ) k End of a string Unassigned chars
12
String Variables Difficulties with this approach:
It can be hard to tell whether an array of characters is being used as a string. String-handling functions must be careful to deal properly with the null character. Finding the length of a string requires searching for the null character.
13
Initializing a String Variable
A string variable can be initialized at the same time it’s declared: char k[12] = "Tom Hanks"; C compiler will fill all the elements not storing the string with null characters '\0' Compiling error if no enough space to store the string End of a string k '\0' hereafter
14
String in a Character Array
A string is exactly characters stored in a character array ended by a null character: The following two statements are equivalent. char k[12] = "Tom Hanks"; char k[12] = {'T', 'o', 'm', ' ', 'H', 'a', 'n', 'k', 's', '\0'}; k End of a string
15
Character Arrays vs. Character Pointers
char date[] = "June 14"; char *datep = "June 14"; date[0] = 'j'; *datep = 'j'; date++; datep++; datep = &date[3]; *datep = 'E'; datep date datep datep
16
13.3 Reading and Writing Strings
printf puts scanf gets getch getche
17
Writing Strings Using printf
The %s conversion specification allows printf to write a string: char str[] = "Are we having fun yet?"; printf("%s\n", str); printf writes the characters in a string one by one until it encounters a null character. Are we having fun yet?
18
Writing Strings Using printf
char color[12] = "blue"; char *p; p = color + 2; printf("%s\n%s\n", color, p); p char[ ] or char * color blue ue
19
Writing Strings Using puts
The C library also provides puts to write strings : puts(str); After writing a string, puts always writes an additional new-line character.
20
Reading Strings Using scanf
The %s conversion specification allows scanf to read a string into a character array: scanf("%s", str); str is treated as a pointer, so there’s no need to put the & operator in front of str.
21
Reading Strings Using scanf
When scanf is called, it skips white space, then reads characters and stores them in str until it encounters a white-space character (space, TAB, newline, etc.) scanf always stores a null character at the end of the string.
22
Reading Strings Using scanf
Ex. char name[12]; scanf("%s", name); %s Pointer to the storing location name M a r y \0 Mary Hanks (← input by the user)
23
Reading Strings Using gets
gets reads an entire line of input. gets(str); Reads until it finds a new-line character. Discards the new-line character instead of storing it; the null character takes its place. str M a r y H a n k s \0 Mary Hanks (← input by the user)
24
Reading Strings In order to avoid reading more characters than one array can save, use fgets() instead of gets().
25
Reading Strings Using fgets
fgets reads an entire line from input until n - 1 characters are read. fgets(str, n, stdin); Reserve the new-line character Append the null character at the end 12 str M a r y H a n k s \n \0 Mary Hanks (← input by the user)
26
Reading Strings Using fgets
fgets reads an entire line from input until n - 1 characters are read. fgets(str, sizeof(str), stdin); Reserve the new-line character Append the null character at the end str M a r i l y n H a n \0 Marilyn Hanks (← input by the user)
27
13.4 Accessing the Characters in a String
Example: a function that counts the number of spaces in a string: int count_spaces(const char s[]) { int count = 0, i; for (i = 0; s[i] != '\0'; i++) if (s[i] == ' ') count++; return count; }
28
Accessing the Characters in a String (with Pointers)
Example: a function that counts the number of spaces in a string: int count_spaces(const char s[]) { int count = 0; char *p; for (p = s; *p != '\0'; p++) if (*p == ' ') count++; return count; }
29
getch() and getche() Functions to read a character from keyboard
They are in conio.h getche(): the typed character will be shown on the screen getch(): the typed character will not be shown on the screen Only for Windows systems
30
Example of Characters #include <stdio.h>
#include <conio.h> int main() { char ch = 'B'; // assign a value of char ch = getche(); // immediately, Windows only printf("你輸入的是:%c\n", ch); scanf("%c", &ch); // action after ENTER return 0; } A你輸入的是:A _
31
Program: Input Characters and Store them in an Array
The program gets a line entered by the user and store them in a character array. When entering the line, all numbers are marked by asterisks (‘*’). Enter a line: It is *:** now. Your line is [It is 2:30 now.]
32
Program: Input Characters and Store them in an Array
#include <stdio.h> #include <conio.h> int main() { char line[100], ch = '\0'; int n = 0; printf("Enter a line: "); do { ch = getch(); putchar('0'<= ch && ch <='9' ? '*' : ch); line[n++] = '\r' == ch ? '\0' : ch; } while (ch != '\r'); printf("Your line is [%s]\n", line); return 0; }
33
Practice Change all the '-' symbols in a string into spaces.
[Home practice] Change all the TAB symbols in a string into spaces. Change all the newline symbols in a string into spaces.
34
13.5 Using C String Library Included in <string.h>
strcpy – to copy strings strlen – to get the length of a string strcat – to concatenate two strings strcmp – to compare two strings …
35
Why Using the C String Library
Direct attempts to copy strings (using =) or compare strings (using ==) will fail. char str1[10], str2[10]; str1 = "abc"; // Wrong: assigning to a constant (array name) str2 = str1; // Wrong: copying pointers, not strings if (str2 == str1)...; // Wrong: checking pointers POINT to the same // location, not checking content of strings
36
strlen To get the length of a string (i.e. number of characters before '\0') Ex: char mystr[18]="Say hello!"; printf("字串長度 %d 個字元\n",strlen(mystr)); 字串長度 10 個字元
37
strlen Note that "length of a string" is different from "size of an array for the string". Ex: char mystr[18]="Say hello!"; String length: 10 Array size: 18
38
strlen int strlen(char *str); p p p p p p p p p p str sent 傳回值 count 9
??? 9 9 8 1 2 7 3 4 6 5 len int main() { char sent[12] = "Tom Hanks"; int len = strlen(sent); return 0; }
39
strcpy and strncpy char k1[12], k2[12]="12345678";
strcpy(char *s1, char *s2): 將 s2 內容copy給 s1 strcpy(k1,"abcdefg"); // k1: "abcdefg" strcpy(k1, k2); // k1: " " strncpy(char *s1, char *s2, int n): 將 s2 中最多 n 個字元 copy 到 s1 strncpy(k1, k2, 4); // k1: "1234efg"
40
strcpy strcpy(char *str1, char *str2); str1 p p p p p p p p k1 str2 q
int main() { char k1[12]; strcpy(k1, "abcdefg"); return 0; }
41
strcpy strcpy(char *str1, char *str2); str1 p p p p p p p p p k1 k2
q q q q q q q q q int main() { char k1[12], k2[12] = " "; strcpy(k1, k2); return 0; }
42
strncpy strncpy(char *str1, char *str2, int n); n str1 p p p p 4 k1 k2
q q q q count 4 3 2 1 int main() { char k1[12], k2[12] = " "; strcpy(k1, "abcdefg"); strncpy(k1, k2, 4); return 0; }
43
strcpy and strncpy char k1[12], k2[12]="12345678";
strcpy(k1,"abcdefg"); // k1: "abcdefg" strncpy(k1, k2, 8); //k1: k1[8] = '\0'; //k1: " " k1 1 2 3 4 5 6 7 8 \0
44
strncpy strncpy(char *str1, char *str2, int n); n str1 p p p p p p p p
8 k1 k2 str2 q q q q q q q q count 6 7 8 5 1 4 2 3 int main() { char k1[12], k2[12] = " "; strcpy(k1, "abcdefg"); strncpy(k1, k2, 8); return 0; }
45
strcmp To compare two strings strcmp(const char *s1, const char *s2):
return 0 if s1 is equal to s2 1 s1 is larger than s2 -1 s1 is smaller than s2 Example: strcmp() return value strcmp("aaa", "abb") strcmp("aaa", "aaa") strcmp("aaa", "aaaa") strcmp("small", "big") -1 1
46
Printable Character
47
Example of strcmp() void main(){ char name[20]; printf("請輸入姓名:");
scanf("%s", name); if (!strcmp(name, "林川傑")){ //表示相等 printf("哦!老師你來亂的喔!\n"); printf("不讓你登入!嘿嘿!\n"); } //比較相等時也可寫 if (strcmp(name, "林川傑")==0)
48
strcmp strcmp(char *str1, char *str2); str1 p p 傳回值 -1 k1 k2 str2 q q
??? -1 int main() { char k1[12] = "aaa", k2[12] = "abb"; int a = strcmp(k1, k2); return 0; }
49
strcmp strcmp(char *str1, char *str2); str1 p p p p 傳回值 k1 k2 str2 q q
k1 k2 str2 q q q q a ??? int main() { char k1[12] = "aaa", k2[12] = "aaa"; int a = strcmp(k1, k2); return 0; }
50
strcmp strcmp(char *str1, char *str2); str1 p p p p 傳回值 -1 k1 k2 str2
q q q q a ??? -1 int main() { char k1[12] = "aaa", k2[12] = "aaaa"; int a = strcmp(k1, k2); return 0; }
51
strcat and strncat char k1[20], k2[12]="12345678";
strcat(char *s1, char *s2): 將 s2 內容 copy 到 s1 的結尾處 strcpy(k1,"abcdefg"); // k1: "abcdefg" strcat(k1, k2); // k1:"abcdefg " strncat(char *s1, char *s2, int n): 將 s2 中最多 n 個字元 copy 到 s1的結尾處 strncat(k1, k2, 4); // k1: '\0'
52
strcat strcat(char *str1, char *str2); str1 p p p p p p p k1 k2 str2 q
int main() { char k1[12], k2[12] = "$$$$"; strcpy(k1, "aa"); strcat(k1, k2); return 0; }
53
Array of Strings char color[3][8]={"blue","yellow","red"}; color
char * * const a constant pointer to pointer to characters color[0] color[1] color[2]
54
Array of Strings char name[3][20]; int i; for (i = 0; i < 3; i++){
printf("請輸入第%d位的姓名:", i + 1); scanf("%s", name[i]); } Same type as char *, Which means &name[i][0] name[0] name[1] name[2]
55
Array of Strings char * color[]={"red","green","blue"};
Note that these strings are not necessarily stored in sequential memory. color[] char *
56
Arrays of Strings char planets[][8] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}; Overhead: unused space for short strings
57
Arrays of Strings char *planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}; Overhead: space for pointers
58
Practice Write a function to check if a given string belongs to a specific set of strings. If so, return its index; otherwise return -1. Example: indexOfStr(planet,8,"Mars") returns 3 indexOfStr(planet,8,"May") returns -1 indexOfStr(color,3,"Mars") returns -1
59
Functions returning Addresses
A function can return an address in a string where a wanted substring is found A function will return NULL to indicate that a wanted substring cannot be found. strchr() strstr() strtok() ...
60
String Search Functions (23.6)
char *strchr(const char *s, int c) 傳回字元 c 在字串 s中第一個出現的位址 如果找不到 c ,回傳NULL char myString[12] = "NT$33-3-4", *p; p = strchr(myString, '-'); p myString
61
strchr p p p p p p s char *strchr(const char *s, int c) {
if (s == NULL) return NULL; char *p = s; while (*p != '\0') { // not the end of the string if (*p == c) return p; p++; } return NULL;
62
strchr char *strchr(const char *s, int c) { if (*p == c) return p; }
if (s == NULL) return NULL; char *p = s; while (*p != '\0') { // not the end of the string if (*p == c) return p; p++; } return NULL; } int main() { char str[12] = "NT$33-3-4", *p; p = strchr(str, '-'); return 0; c - p s return value p 怪怪 str
63
String Search Functions (Cont.)
char *strstr(const char *s1, const char *s2) 傳回字串 s2 在字串 s1中第一個出現的位址 如果找不到任何出現 ,回傳NULL char myString[12]="NT$33-3-4", *p; p=strstr(myString,"3-"); p[strlen("3-")]='\0'; printf("%s\n",p); p myString '\0'
64
Practice Change all the occurrences of "," in a string into ", ".
65
String Search Functions (Cont.)
char *strtok(char *s1, const char *s2) Separate the string s1 into tokens At the first time you call strtok(), pass the address of the string s1 as the first parameter. Beginning at the second time when you call, pass NULL as the first parameter. Tokens are separated by the characters in the string s2. strtok() will return the starting address of next token at each time. The end of a token will be modified as '\0' in the original string. (原字串會被修改) When no more tokens are found, return NULL.
66
Example of strtok() char myString[]="6-foot boy";
char punc[]=",.! -?", *p; p=strtok(myString, punc); // first call while ( p != NULL ){ printf("token: %s\n", p); p=strtok(NULL, punc); // get next token } token: 6 token: foot token: boy p NULL '\0' '\0' myString
67
Practice Chunk tokens in a sentence according to the space (' ') and newline ('\n'), and print out these tokens. char sentence[100]= "This is a good day.\nLet's go hiking!\n";
68
中文 BIG5 碼 每個中文字是由兩個 bytes 所組成 中文的編碼有三區,每一區都照筆劃排列
69
中文字串 例:"卡拉OK" 卡 拉 O K
70
尋找字串會出的錯 strstr( "物流" , "型" ) "物流": AA AB AC 79 "型": AB AC 傳回值 物 型 流
71
比大小會出的錯 char ch1='\xa4', ch2='\x66';
(signed int)'\xa4'= -91 (signed int)'\x66'= 102 102 > -91 unsigned char ch1='\xa4', ch2='\x66'; (unsigned signed int)'\xa4'= 164 (unsigned signed int)'\x66'= 102 164 > 102
72
大小寫會出的錯 有些大於128的字元涵蓋了某些西歐字母。 例: àáâã 0xE0, 0xE1, 0xE2, 0xE3
ÀÁÂÃ 0xC0, 0xC1, 0xC2, 0xC3 "分" (0xA4C0), "戈" (0xA4E0) 在忽略大小寫的比對時會被相同字串
73
Unicode 碼 所有字元皆由兩個 bytes 所組成 文中會出現 Null character ('\0') 不易與之前格式對應
拉丁字母、標點及符號 各國特殊字元,包含中日韓表意文字 文中會出現 Null character ('\0') 不易與之前格式對應 仍有部份比對的問題
74
Unicode字串 例:"卡拉OK" 卡 拉 O K
75
UTF-8 碼 將 Unicode 對應至變動長度的編碼方式 不會出現 Null character ('\0') 不會有部份比對的問題
拉丁字母、標點及符號長度為 1 byte 中日韓表意文字長度為 3 bytes 不會出現 Null character ('\0') 不會有部份比對的問題 中文文章長度變長
76
UTF-8字串 例:"卡拉OK" 卡 拉 O K
77
Pointers to Pointers If you want a function to modify the value of a pointer, you need to pass the address of the pointer as a parameter. void myf(char ** p); int main(){ char * myp; myf( &myp ); ... } p myp ???
78
Pointers to Pointers Write a function to find the first and the last positions of a character in a string. void myf(char *str, char c, char **p, char **q); int main() { char sent[] = "To be or not to be."; char *firstp, *lastp; myf(sent, 'e', &firstp, &lastp); return 0; } sent firstp lastp
79
void myf(char *str, char c, char **p, char **q){ char *a = str;
while (*a != '\0' && *a != c) a++; *p = *a == c ? a : NULL; a = str; while (*a != '\0') a++; while (a >= str && *a != c) a--; *q = a >= str ? a : NULL; } int main() { char sent[] = "To be or not to be."; char *firstp, *lastp; myf(sent, 'e', &firstp, &lastp); return 0; a a a a a a a a a a a a a a a a a a a a sent str p q firstp ??? ??? lastp
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.