แปลงเฉพาะตัวอักษรสระ (Vowels: a, e, i, o, u) ในสตริง ให้สลับ Case (Uppercase ↔ Lowercase)
ตรรกะการแปลง
for(i = 0; str[i] != '\0'; i++) {
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' ||
str[i] == 'O' || str[i] == 'U') {
if(islower(str[i]))
str[i] = toupper(str[i]);
else
str[i] = tolower(str[i]);
}
}
ตัวอย่างโปรแกรมครบถ้วน
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char str[100];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // ลบ newline
for(int i = 0; str[i] != '\0'; i++) {
char c = str[i];
// ตรวจสอบว่เป็นสระหรือไม่ (ทั้งพิมพ์ใหญ่และเล็ก)
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
if(islower(c))
str[i] = toupper(c);
else
str[i] = tolower(c);
}
}
printf("Result: %s\n", str);
return 0;
}
ผลลัพธ์
Run 1: Enter string: TutoRialsPoint Result: TUtORIAlsPOInt Run 2: Enter string: c programming Result: c programming (ไม่มีสระพิมพ์ใหญ่ จึงไม่เปลี่ยน)
วิธี Alternative: ใช้ ASCII/bitwise
// สลับ Case ด้วย XOR 32 (0x20) - ใช้ได้เฉพาะ ASCII Letters
if(isalpha(c) && (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')) {
str[i] ^= 32; // Toggle bit 5
}
ขยาย: นับจำนวนสระที่เปลี่ยน
int vowel_count = 0;
for(int i = 0; str[i]; i++) {
char c = tolower(str[i]);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowel_count++;
// Toggle case...
}
}
printf("Vowels converted: %d\n", vowel_count);
ฟังก์ชัน Helper แบบ Reusable
int is_vowel(char c) {
c = tolower(c);
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
void toggle_vowels(char *str) {
for(int i = 0; str[i]; i++) {
if(is_vowel(str[i])) {
str[i] = islower(str[i]) ? toupper(str[i]) : tolower(str[i]);
}
}
}