In questo tutorial imparerai a usare i caratteri e le stringhe in Swift. Imparerai anche diverse operazioni che possono essere eseguite su stringhe e caratteri.
Cos'è un personaggio?
Un carattere è un singolo simbolo (lettera, numero, ecc.). I caratteri in swift sono di Character
tipo ed è dichiarato come:
let someCharacter: Character
Come dichiarare e assegnare un personaggio in Swift?
È possibile assegnare un valore in Tipo di carattere uguale a Stringa utilizzando virgolette doppie, " "
ma dovrebbe contenere solo un singolo carattere tra virgolette " "
.
Se è necessario includere più di un carattere, è necessario definirlo String
invece di Character
.
Esempio 1: dichiarazione e assegnazione di un personaggio
let someCharacter:Character = “H” let specialCharacter:Character = “@” print(someCharacter) print(specialCharacter)
Quando esegui il programma, l'output sarà:
H @
Esempio 2: assegnazione di più di un carattere (non funziona)
Ma se provi ad assegnare due simboli all'interno del carattere come
/* This will give an error Changing the type to String will fix it. */ let failableCharacter:Character = "H@" print(failableCharacter)
Quando provi a eseguire il codice sopra, riceverai un errore come:
Impossibile convertire il valore di tipo String in Character.
Creazione di caratteri utilizzando Unicode e sequenza di escape
Puoi anche creare caratteri speciali per.eg emoji usando unicodes. Puoi creare un Unicode usando la sequenza di escape u (n) (punto di codice Unicode, n è in esadecimale).
Esempio 3: creazione di un carattere Unicode
let heartShape:Character = "u(2665)" print(heartShape)
Quando esegui il programma, l'output sarà:
♥
Nell'esempio precedente, un carattere a forma di cuore è stato creato dal codice U+2665
. Sebbene u(2665)
sia incluso tra virgolette doppie, il compilatore non lo considera come un String
perché abbiamo usato la sequenza di escape u(n)
. Una sequenza di escape non rappresenta se stessa quando inclusa nel letterale.
Cos'è una stringa?
Una stringa è semplicemente una raccolta di caratteri. Le stringhe in Swift sono di String
tipo e dichiarate come:
let someString: String
Come dichiarare e assegnare una stringa in Swift?
È possibile assegnare un valore in tipo String utilizzando stringhe letterali. Una stringa letterale è una raccolta di caratteri racchiusi tra virgolette doppie " "
.
Esempio 4: dichiarazione e assegnazione di una stringa
let someString:String = "Hello, world!" let someMessage = "I love Swift." print(someString) print(someMessage)
Quando esegui il programma, l'output sarà:
Ciao mondo! Amo Swift.
Qui, entrambi "Hello, world!"
e "I love Swift."
sono letterali stringa utilizzati per creare variabili stringa, rispettivamente, someString e someMessage.
Operazioni su una stringa
Ci sono alcune funzioni e proprietà incorporate in String per gestire le operazioni usate più di frequente. Ad esempio: per unire stringhe, cambialo in maiuscolo o in maiuscolo. Esploriamo di seguito alcune operazioni utilizzate di frequente:
Confronto di stringhe
Puoi semplicemente controllare se due stringhe sono uguali o meno utilizzando l'operatore di confronto (==)
. L'operatore restituisce restituisce true
se entrambe le stringhe sono uguali, altrimenti restituisce false
.
Esempio 5: confronto di stringhe in Swift
let someString = "Hello, world!" let someMessage = "I love Swift." let someAnotherMessage = "Hello, world!" print(someString == someMessage) print(someString == someAnotherMessage)
Quando esegui il programma, l'output sarà:
falsa verità
Concatenazione di stringhe
È possibile aggiungere due diversi valori di stringhe insieme all'operatore di addizione (+)
o utilizzando l'operatore di assegnazione composto (+=)
. Puoi anche aggiungere un carattere / una stringa in una stringa usando il append
metodo.
Esempio 6: concatenazione di stringhe in Swift
let helloStr = "Hello, " let worldStr = "World" var result = helloStr + worldStr print(result) result.append("!") print(result)
Quando esegui il programma, l'output sarà:
Ciao, mondo Ciao, mondo!
Nel programma sopra abbiamo creato un risultato stringa aggiungendo helloStr e worldStr usando l'operatore +. Quindi, print(result)
uscite Ciao, Mondo nella schermata.
Puoi anche aggiungere qualsiasi carattere o stringa usando il append
metodo. result.append("!")
aggiunge un !
carattere alla fine della stringa. Quindi, le print(result)
uscite Hello, World! sullo schermo.
Concatenazione di stringhe utilizzando l'operatore di assegnazione avanzato
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
Questa funzione determina se una stringa inizia con determinati caratteri o meno e restituisce un valore booleano. Restituisce true
se il prefisso della stringa corrisponde al valore fornito, altrimenti restituisce false
.
Esempio 13: hasPrefix ()
let someString = "Hello, World!" print(someString.hasPrefix("Hell")) print(someString.hasPrefix("hell"))
Quando esegui il programma, l'output sarà:
vero falso
6. hasSuffix
Questa funzione determina se una stringa termina con determinati caratteri o meno e restituisce un valore booleano. Restituisce true
se il suffisso della stringa corrisponde al valore fornito, altrimenti restituisce false
.
Esempio 14: hasSuffix ()
print(someString.hasSuffix("rld!")) print(someString.hasSuffix("Rld!"))
Quando esegui il programma, l'output sarà:
vero falso