Šajā apmācībā jūs uzzināsit par rakstzīmju un virkņu lietošanu programmā Swift. Jūs arī uzzināsiet dažādas darbības, kuras var veikt ar virknēm un rakstzīmēm.
Kas ir raksturs?
Raksts ir viens simbols (burts, cipars utt.). Raksturs ātri ir Character
tipa un tiek deklarēts kā:
let someCharacter: Raksturs
Kā deklarēt un piešķirt rakstzīmi Swift?
Jūs varat piešķirt vērtību rakstura tips tāpat kā String izmantojot pēdiņas " "
, bet tam vajadzētu būt tikai vienu rakstzīmi iekšpusē pēdiņām " "
.
Ja jums jāiekļauj vairāk nekā viena rakstzīme, tā String
vietā jādefinē Character
.
1. piemērs: rakstzīmes deklarēšana un piešķiršana
let someCharacter:Character = “H” let specialCharacter:Character = “@” print(someCharacter) print(specialCharacter)
Palaidot programmu, izeja būs:
H @
2. piemērs: vairāku rakstzīmju piešķiršana (nedarbojas)
Bet, ja jūs mēģināt piešķirt divus simbolus rakstzīmes iekšpusē kā
/* This will give an error Changing the type to String will fix it. */ let failableCharacter:Character = "H@" print(failableCharacter)
Mēģinot palaist iepriekš minēto kodu, tiks parādīta kļūda:
Nevar pārveidot virknes String vērtību par Character.
Rakstzīmju izveide, izmantojot unikoda un aizbēgšanas secību
Izmantojot unikodus, varat arī izveidot īpaša veida rakstzīmes for.eg emocijzīmēm. Varat izveidot unikodu, izmantojot evakuācijas secību u (n) (unikoda koda punkts, n ir heksadecimāls).
3. piemērs: unikoda rakstzīmes izveide
let heartShape:Character = "u(2665)" print(heartShape)
Palaidot programmu, izeja būs:
♥
Iepriekš minētajā piemērā sirds formas raksturs tika izveidots no koda U+2665
. Lai gan tas u(2665)
ir iekļauts dubultās pēdiņās, kompilators to neuzskata par String
tāpēc, ka mēs izmantojām aizbēgšanas secību u(n)
. Bēgšanas secība neatspoguļo sevi, ja tā ir iekļauta burtiskajā.
Kas ir stīga?
Virkne ir vienkārši rakstzīmju kolekcija. Stīgas Swift ir String
veida un deklarētas kā:
let someString: Stīga
Kā deklarēt un piešķirt virkni programmā Swift?
Izmantojot virknes literālus, vērtību var piešķirt virknes tipā. Stīgu literālis ir rakstzīmju kopums, kas ieskauts ar dubultām pēdiņām " "
.
4. piemērs: Virknes deklarēšana un piešķiršana
let someString:String = "Hello, world!" let someMessage = "I love Swift." print(someString) print(someMessage)
Palaidot programmu, izeja būs:
Sveika pasaule! Es mīlu Sviftu.
Šeit abi "Hello, world!"
un "I love Swift."
ir virknes literāļi, kurus izmanto, lai izveidotu virkņu mainīgos attiecīgi someString un someMessage.
Darbības ar virkni
String ir dažas iebūvētas funkcijas un īpašums, lai tiktu galā ar visbiežāk izmantotajām operācijām. Piemēram: lai pievienotos virknēm, mainiet to uz lielajiem burtiem vai ar lielajiem burtiem. Tālāk izpētīsim dažas bieži izmantotās darbības:
Stīgu salīdzinājums
Izmantojot salīdzināšanas operatoru, varat vienkārši pārbaudīt, vai divas virknes ir vienādas vai nav (==)
. Operators atgriež atgriešanos, true
ja abas virknes ir vienādas, pretējā gadījumā tas atgriežas false
.
5. piemērs: Stīgu salīdzinājums programmā Swift
let someString = "Hello, world!" let someMessage = "I love Swift." let someAnotherMessage = "Hello, world!" print(someString == someMessage) print(someString == someAnotherMessage)
Palaidot programmu, izeja būs:
nepatiesa taisnība
Stīgu savienošana
Divas dažādas virkņu vērtību var pievienot kopā ar pievienošanas operatoru (+)
vai izmantojot salikuma piešķiršanas operatoru (+=)
. Varat arī pievienot rakstzīmi / virkni virknē, izmantojot append
metodi.
6. piemērs: Stīgu savienošana Swift
let helloStr = "Hello, " let worldStr = "World" var result = helloStr + worldStr print(result) result.append("!") print(result)
Palaidot programmu, izeja būs:
Sveiki, pasaule Sveiki, pasaule!
Iepriekš minētajā programmā mēs izveidojām virknes rezultātu, pievienojot helloStr un worldStr, izmantojot + operatoru. Tātad, print(result)
izejas Sveiki, World ekrānā.
Izmantojot append
metodi, varat pievienot arī jebkuru rakstzīmi vai virkni . virknes beigās result.append("!")
pievieno !
rakstzīmi. Tātad, print(result)
rezultāti Sveika, pasaule! uz ekrāna.
Virknes savienošana, izmantojot uzlabotu piešķiršanas operatoru
We can also use advanced assignment operator (+=) to append string.
Example 7: String concatenation using += operator
var helloStr = "Hello, " let worldStr = "World!" helloStr += worldStr print(helloStr)
When you run the program, the output will be:
Hello, World!
Notice the use of var instead of let in helloStr. If you have defined helloStr a constant using let, you cannot change it later using the +=
operator and eventually get an error. So, you have to define helloStr a variable.
String Interpolation
It is a simple process of evaluating a string literal that consists of variables, constants etc. Imagine you have player’s name and score stored in two constants as:
let playerName = "Jack" let playerScore = 99
Now you need to display a message to the player as "Congratulations Jack!. Your highest score is 99." Here, you need to a way to use the values of the constants in a single string.
This can be achieved using string concatenation as:
let congratsMessage = "Congratulations " + playerName + "!. Your highest score is " + playerScore + "." print(congratsMessage)
However, you can see this can get messy pretty soon. You have to take care of the spaces after the word Congratulations
, is
. Also, if you have to use more than two constants/variables, it will get unreadable.
There’s an easier way to display the message using string interpolation. Interpolation is the process to include value of a variable or constant inside string literal.
The variable or constant that should insert into the string literal is wrapped in a pair of parentheses ( )
, prefixed by a backslash ()
.
Example 8: String interpolation in Swift
let playerName = "Jack" let playerScore = 99 let congratsMessage = "Congratulations (playerName)!. Your highest score is (playerScore)." print(congratsMessage)
When you run the program, the output will be:
Congratulations Jack!. Your highest score is 99.
Some helpful built-in String functions & variables:
1. isEmpty
This function determines if a string is empty or not. It returns true
if the string is empty otherwise, it returns false
.
Example 9: isEmpty
var emptyString = "" print(emptyString.isEmpty)
When you run the program, the output will be:
true
2. capitalized
This property is used to capitalize every word in a string.
Example 10: capitalized
let someString = "hello, world!" print(someString.capitalized)
When you run the program, the output will be:
Hello, World!
3. uppercased and lowercased
The uppercased function converts string to uppercase letter and the lowercased function converts string to lowercase letter.
Example 11: uppercased() and lowercased()
let someString = "Hello, World!" print(someString.uppercased()) print(someString.lowercased())
When you run the program, the output will be:
HELLO, WORLD! hello, world!
4. Length/count
This property is used to count the total number of characters in a string.
Example 12: count
let someString = "Hello, World!" print(someString.count)
When you run the program, the output will be:
13
5. hasPrefix
Šī funkcija nosaka, vai virkne sākas ar noteiktām rakstzīmēm, vai ne, un atgriež Būla vērtību. Tas atgriežas, true
ja virknes prefikss sakrīt ar norādīto vērtību, citādi atgriežoties false
.
13. piemērs: hasPrefix ()
let someString = "Hello, World!" print(someString.hasPrefix("Hell")) print(someString.hasPrefix("hell"))
Palaidot programmu, izeja būs:
patiess melīgs
6. hasSuffix
Šī funkcija nosaka, vai virkne beidzas ar noteiktām rakstzīmēm, vai ne, un atgriež Būla vērtību. Tas atgriežas, true
ja virknes sufikss atbilst norādītajai vērtībai false
.
14. piemērs: hasSuffix ()
print(someString.hasSuffix("rld!")) print(someString.hasSuffix("Rld!"))
Palaidot programmu, izeja būs:
patiess melīgs