使用迴圈顯示字母(A 到 Z)的 Swift 程式


本教程將討論如何編寫一個 Swift 程式,使用迴圈顯示字母(A 到 Z)。

在 Swift 中,我們可以藉助 for 迴圈以大小寫兩種方式顯示從 A 到 Z 的字母。在下面的程式碼中,我們使用了以下術語:

標量 - 它表示單個值。

Unicode - 它是文字的標準編碼。

UnicodeScalar - 它表示單個 Unicode 標量值。

以下是相同內容的演示:

假設我們輸入以下內容:

A to Z

以下是所需的輸出:

A B C D E F G H I J K L M N LO P Q R S T U V W X Y Z

演算法

演算法解釋如下:

  • 步驟 1 - 使用 Unicode.Scalar.value 宣告具有 Unicode 標量值的變數:

    let initalAlphabet = Unicode.Scalar("A").value

    let endAlphabet = Unicode.Scalar(“Z").value

    這裡,Unicode.Scalar.value 返回 A 和 Z 的 Unicode 值,分別為 65 和 90。

  • 步驟 2 - 執行 for 迴圈

  • 步驟 3 - 列印輸出

示例 1

以下程式演示瞭如何使用 for 迴圈以大寫形式顯示字母(A 到 Z)。

import Foundation import Glibc let initalAlphabet = Unicode.Scalar("A").value let endAlphabet = Unicode.Scalar("Z").value print("Following are the alphabets from A to Z:") for k in initalAlphabet...endAlphabet { if let val = Unicode.Scalar(k) { print(val) } }

輸出

Following are the alphabets from A to Z:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

在上面的程式碼中,我們建立了兩個名為 initalAlphabet = Unicode.Scalar("A").value 和 endAlphabet = Unicode.Scalar(“Z”).value 的變數,其中 Unicode.Scalar(“A").value 返回 'A' 的 ASCII 值 65,Unicode.Scalar(“Z”).value 返回 'Z' 的 ASCII 值 90。現在我們執行一個從 65 到 90 的 for 迴圈,並使用以下程式碼顯示從 A 到 Z 的所有字母:

if let val = Unicode.Scalar(k) {
   print(val)
}

這裡 Unicode.Scalar() 將所有 ASCII 值轉換為字母。

示例 2

以下程式演示瞭如何使用 for 迴圈以小寫形式顯示字母(A 到 Z)。

import Foundation import Glibc print("Following are the alphabets from a to z:") for char in "abcdefghijklmnopqrstuvwxyz" { print(char) }

輸出

Following are the alphabets from a to z:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

在上面的程式碼中,我們簡單地建立了一個包含字串中所有字母的 for 迴圈,並分別顯示每個字母。

示例 3

以下程式演示瞭如何使用 for 迴圈以小寫形式顯示字母(A 到 Z)。

import Foundation import Glibc print("Following are the Alphabets: ") for val in UnicodeScalar("a").value...UnicodeScalar("z").value{ print(UnicodeScalar(val)!) }

輸出

Following are the Alphabets: 
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

在上面的程式碼中,我們建立了一個從 UnicodeScalar(“a").value 到 UnicodeScalar(“z”).value 的 for 迴圈,並顯示所有字母。其中 UnicodeScalar().value 返回“a”和“z”的 ASCII 值。UnicodeScalar() 函式用於將 ASCII 轉換為字元。

更新於: 2022-08-05

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.