Weitere ähnliche Inhalte
Mehr von mr.somsak phoolpherm (9)
4 3
- 1. แบบฝกทักษะการเขียนโปรแกรมภาษาซี เลม 4 ฟงกชันนารู
กลุมฟงกชันเกี่ยวกับอักขระ
#include <ctype.h>
ฟงกชันในกลุมนี้จะตรวจสอบวาคาที่ปอนมานั้นเปนตัวอักขระ ตัวเลข ตัวพิมพเลข
พิมพใหญ ซึ่งจะมีประโยชนมากสําหรับการเขียนโปรแกรมเพือบังคับใหผูใชกรอกขอมูลที่
่
ตองการได
ฟงกชัน
islower(x)
isupper(x)
isalpha(x)
isdigit(x)
tolower(x)
toupper(x)
ประโยชนการใชงาน
ตรวจสอบคา x วาเปนอักษรพิมพเล็กหรือไม
ตรวจสอบคา x วาเปนอักษรพิมพใหญหรือไม
ตรวจสอบคา x วาเปนอักขระ a-z หรือ A-Z หรือไม
ตรวจสอบคา x วาเปนตัวเลข 0-9 หรือไม
แปลงอักขระ x ใหเปนตัวพิมพเล็ก
แปลงอักขระ x ใหเปนตัวพิมพใหญ
15
- 2. แบบฝกทักษะการเขียนโปรแกรมภาษาซี เลม 4 ฟงกชันนารู
ตัวอยางโปรแกรมที่ 4.7 การใชงาน islower(),isupper(),isalpha() และ isdigit()
บรรทัดที่
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
คําสั่ง
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
main() {
char ch = ' ', ch = 'K',ch ='a', ch = '*';
printf("islower(%c) = %dn",ch ,islower(ch ));
printf("islower(%c) = %dn",ch ,islower(ch ));
printf("islower(%c) = %dn",ch ,islower(ch ));
printf("isupper(%c) = %dn",ch ,isupper(ch ));
printf("isupper(%c) = %dn",ch ,isupper(ch ));
printf("isupper(%c) = %dn",ch ,isupper(ch ));
printf("isalpha(%c) = %dn",ch ,isalpha(ch ));
printf("isalpha(%c) = %dn",ch ,isalpha(ch ));
printf("isalpha(%c) = %dn",ch ,isalpha(ch ));
printf("isalpha(%c) = %dn",ch ,isalpha(ch ));
printf("isdigit(%c) = %dn",ch ,isdigit(ch ));
printf("isdigit(%c) = %dn",ch ,isdigit(ch ));
printf("isdigit(%c) = %dn",ch ,isdigit(ch ));
getch();
}
16
- 3. แบบฝกทักษะการเขียนโปรแกรมภาษาซี เลม 4 ฟงกชันนารู
บรรทัดที่ 5 กําหนดให ch1= ‘9’ , ch = 'K',ch ='a', ch = '*'
บรรทัดที่ 6-8 แสดงคา ch1-ch3 ผานฟงกชัน islower()
บรรทัดที่ 9-11 แสดงคา ch1-ch3 ผานฟงกชัน isupper()
บรรทัดที่ 12-15 แสดงคา ch1-ch4 ผานฟงกชัน isalpha()
บรรทัดที่ 16-18 แสดงคา ch1-ch3 ผานฟงกชัน isdigit()
ผลการรันโปรแกรม
ขอสังเกต คาที่ผานการตรวจสอบถาเปน
เท็จตัวฟงกชันจะสงคาคืนมาเปน 0 สวน
คาที่ตรวจสอบแลวเปนจริงจะสงคาที่ไมใช 0
17
- 4. แบบฝกทักษะการเขียนโปรแกรมภาษาซี เลม 4 ฟงกชันนารู
ตัวอยางโปรแกรมที่ 4.7 การใช tolower และ toupper
บรรทัดที่
คําสั่ง
1
#include <stdio.h>
2
#include <conio.h>
3
#include <ctype.h>
4
main() {
5
char ch = 'a', ch = 'b', ch = 'c';
6
char ch = 'X', ch = 'Y', ch = 'Z';
7
printf("Uppercase = %c",toupper(ch ));
8
printf("%c",toupper(ch ));
9
printf("%cn",toupper(ch ));
10
printf("Lowercase = %c",tolower(ch ));
11
printf("%c",tolower(ch ));
12
printf("%cn",tolower(ch ));
13
getch();
14
}
บรรทัดที่ 5 กําหนดตัวแปร ch1,ch2,ch3 เปนอักขระพิมพเล็ก
บรรทัดที่ 6 กําหนดตัวแปร ch4,ch5,ch6 เปนอักขระพิมพใหญ
บรรทัดที่ 7-9 แสดงคา ของตัวแปร ch1,ch2,ch3 ผานฟงกชัน toupper()
บรรทัดที่ 10-12 แสดงคา ของตัวแปร ch4,ch5,ch6 ผานฟงกชัน tolower()
ผลการรันโปรแกรม
18