Swift程式演示如何在字串中編寫雙引號


在Swift中,字串是由雙引號括起來的字元序列,例如:“Learn Swift”、“tutorialspoint”等。但是,當您列印字串時,編譯器會移除雙引號,您將得到Learn Swift、tutorialspoint作為輸出。

因此,如果您想在輸出中列印雙引號,則必須在要在給定字串內列印的雙引號之前放置反斜槓字元或跳脫字元(\)。它告訴編譯器該字元應被視為字面字元,而不是字串語法的組成部分。雙引號之前的反斜槓也稱為雙引號字元(\")。

示例

Input: "Today is "Raining""
Output: Today is "Raining"

這裡,跳脫字元位於雙引號之前,因此雙引號被視為字面量,而不是語法的一部分。

示例1

在下面的Swift程式中,我們將演示如何在字串中編寫雙引號。為此,我們將在雙引號之前使用跳脫字元。

import Foundation
import Glibc

let myStr1 = "Birds are playing in the \"rain"
print("String 1:", myStr1)

let myStr2 = "Ram is good \"IOS developer\""
print("String 2:", myStr2)

let myStr3 = "Sita uses double quotes(\"\")"
print("String 3:", myStr3)

輸出

String 1: Birds are playing in the "rain
String 2: Ram is good "IOS developer"
String 3: Sita uses double quotes("")

示例2

在下面的Swift程式中,我們將演示如何在字串中編寫雙引號。因此,在處理多行時,我們不需要使用雙引號字元(\")。我們只需簡單地在要突出顯示的單詞上使用雙引號,編譯器將顯示結果而不會出現任何錯誤。

import Foundation
import Glibc

let InputString = """
Hello Tow
Do you like to play "Football"?
No i dont like "Football"

"""

print(InputString)

輸出

Hello Tow
Do you like to play "Football"?
No i dont like "Football"

結論

這就是我們在字串中編寫雙引號的方法。使用反斜槓字元(\),我們一次只能顯示一個雙引號;如果您想顯示多個雙引號,則必須在每個引號之前使用反斜槓,例如:\" \" \"。當您想在輸出字串中突出顯示某些特定單詞時,可以使用雙引號。如果您想列印單引號,則可以使用(\')。

更新於:2023年6月14日

瀏覽量:239

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.