Skip to Content
CoursesCSC102การเข้ารหัสข้อความด้วยการสลับตัวพิมพ์

การเข้ารหัสข้อความด้วยการสลับตัวพิมพ์

โจทย์

Encryption of each word in the message by the following steps:

  • Alternating uppercase and lowercase (start with uppercase then lowercase).
  • Move all lower cases to the front followed by all uppercase.

The input consists of the number of words in a sentence followed by the sentence. The output is the encrypted message.

InputOutput
3
Programming is fun
rgamnPORMIG sI uFN

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String[] words = new String[n]; for (int i = 0; i < n; i++) { words[i] = scanner.next(); } for (String word: words) { String lowercase = ""; String uppercase = ""; for (int i = 0; i < word.length(); i++) { if (i % 2 == 1) { lowercase += "" + word.toLowerCase().charAt(i); } else { uppercase += "" + word.toUpperCase().charAt(i); } } System.out.print(lowercase + uppercase + " "); } } }

คำอธิบาย

1. การรับข้อมูล

int n = scanner.nextInt(); String[] words = new String[n]; for (int i = 0; i < n; i++) { words[i] = scanner.next(); }
  • รับจำนวนคำ
  • สร้างอาร์เรย์เก็บคำ
  • รับคำทีละคำ

2. การเข้ารหัสแต่ละคำ

for (String word: words) { String lowercase = ""; // เก็บตัวพิมพ์เล็ก String uppercase = ""; // เก็บตัวพิมพ์ใหญ่ for (int i = 0; i < word.length(); i++) { if (i % 2 == 1) { // ตำแหน่งคี่ = ตัวพิมพ์เล็ก lowercase += "" + word.toLowerCase().charAt(i); } else { // ตำแหน่งคู่ = ตัวพิมพ์ใหญ่ uppercase += "" + word.toUpperCase().charAt(i); } } System.out.print(lowercase + uppercase + " "); }

แผนภาพการทำงาน

ตัวอย่างการทำงาน

กรณี 1: คำว่า “hello”

  1. ขั้นตอนที่ 1: สลับตัวพิมพ์
H e L l O
  1. ขั้นตอนที่ 2: แยกและรวม
  • ตัวพิมพ์เล็ก: “el”
  • ตัวพิมพ์ใหญ่: “HLO”
  • ผลลัพธ์: “elHLO”

กรณี 2: คำว่า “world”

  1. ขั้นตอนที่ 1: สลับตัวพิมพ์
W o R l D
  1. ขั้นตอนที่ 2: แยกและรวม
  • ตัวพิมพ์เล็ก: “ol”
  • ตัวพิมพ์ใหญ่: “WRD”
  • ผลลัพธ์: “olWRD”
ปรับปรุงล่าสุด