In questo articolo imparerai a conoscere le stringhe di Kotlin, i modelli di stringhe e alcune proprietà e funzioni di stringhe comunemente usate con l'aiuto di esempi.
Kotlin String
Le stringhe sono una sequenza di caratteri. Ad esempio, "Hello there!"
è una stringa letterale.
In Kotlin, tutte le stringhe sono oggetti di String
classe. Significa che i valori letterali stringa come "Hello there!"
sono implementati come istanze di questa classe.
Come creare una variabile String?
Ecco come puoi definire una String
variabile in Kotlin. Per esempio,
val myString = "Ciao!"
Qui, myString è una variabile di tipo String
.
È possibile dichiarare la variabile di tipo String
e specificarne il tipo in un'istruzione e inizializzare la variabile in un'altra istruzione più avanti nel programma.
val myString: String … myString = "Howdy"
Come accedere ai caratteri di una stringa?
Per accedere agli elementi (carattere) di una stringa, viene utilizzato l'operatore di accesso all'indice. Per esempio,
val myString = "Ciao!" val item = myString (2)
Qui, la variabile item contiene y, terzo carattere della stringa myString. È perché l'indicizzazione in Kotlin inizia da 0 e non da 1.
val myString = "Ciao!" var item: Char item = myString (0) // item contains "H" item = myString (9) // item contains "!" item = myString (10) // Errore! L'indice della stringa è fuori intervallo item = myString (-1) // Errore! L'indice della stringa è fuori intervallo
Esempio: itera su una stringa
Se hai bisogno di scorrere gli elementi di una stringa, puoi farlo facilmente usando un ciclo for.
fun main(args: Array) ( val myString = "Hey!" for (item in myString) ( println(item) ) )
Quando esegui il programma, l'output sarà:
H e y !
Le stringhe in Kotlin sono immutabili
Come Java, le stringhe sono immutabili in Kotlin. Ciò significa che non è possibile modificare il carattere individuale di una stringa. Per esempio,
var myString = "Hey!" myString (0) = 'h' // Errore! stringhe
Tuttavia, puoi riassegnare di nuovo una variabile stringa se hai dichiarato la variabile utilizzando la parola chiave var
. ( Letture consigliate : Kotlin var Vs val)
Esempio: riassegnazione di una variabile stringa.
fun main(args: Array) ( var myString = "Hey!" println("myString = $myString") myString = "Hello!" println("myString = $myString") )
Quando esegui il programma, l'output sarà:
myString = Hey! myString = Ciao!
Valori letterali stringa
Un letterale è la rappresentazione del codice sorgente di un valore fisso. Ad esempio, "Hey there!"
è una stringa letterale che appare direttamente in un programma senza richiedere calcoli (come le variabili).
Esistono due tipi di stringhe letterali in Kotlin:
1. Stringa di escape
Una stringa con escape potrebbe contenere caratteri di escape. Per esempio,
val myString = "Ciao! n"
Ecco un carattere di escape che inserisce una nuova riga nel testo dove appare.
Ecco un elenco di caratteri di escape supportati in Kotlin:
- Inserisce backspace
- Inserisce una nuova riga
- Inserisce il ritorno a capo
\'
- Inserisce virgolette singole"
- Inserisce virgolette doppie\
- Inserisce il backslash$
- Inserisce il carattere del dollaro
2. Stringa grezza
A raw string can contain newlines (not new line escape character) and arbitrary text. A raw string is delimited by a triple quote """
. For example,
fun main(args: Array) ( val myString = """ for (character in "Hey!") println(character) """ print(myString) )
When you run the program, the output will be:
for (character in "Hey!") println(character)
You can remove the leading whitespaces of a raw string using trimMargin() function. For example,
Example: Printing Raw String
fun main(args: Array) ( println("Output without using trimMargin function:") val myString = """ |Kotlin is interesting. |Kotlin is sponsored and developed by JetBrains. """ println(myString) println("Output using trimMargin function:") println(myString.trimMargin()) )
When you run the program, the output will be:
Output without using trimMargin function: |Kotlin is interesting. |Kotlin is sponsored and developed by JetBrains. Output using trimMargin function: Kotlin is interesting. Kotlin is sponsored and developed by JetBrains.
By default, trimMargin()
function uses | as margin prefix. However, you can change it by passing a new string to this function.
Example: trimMargin() with Argument
fun main(args: Array) ( val myString = """ !!! Kotlin is interesting. !!! Kotlin is sponsored and developed by JetBrains. """ println(myString.trimMargin("!!! ")) )
When you run the program, the output will be:
Kotlin is interesting. Kotlin is sponsored and developed by JetBrains.
Kotlin String Templates
Kotlin has an awesome feature called string templates that allows strings to contain template expressions.
A string template expression starts with a dollar sign $
. Here are few examples:
Example: Kotlin String Template
fun main(args: Array) ( val myInt = 5; val myString = "myInt = $myInt" println(myString) )
When you run the program, the output will be:
myInt = 5
It is because the expression $myInt (expression starting with $ sign) inside the string is evaluated and concatenated into the string.
Example: String Template With Raw String
fun main(args: Array) ( val a = 5 val b = 6 val myString = """ |$(if (a> b) a else b) """ println("Larger number is: $(myString.trimMargin())") )
When you run the program, the output will be:
Larger number is: 6
Few String Properties and Functions
Since literals in Kotlin are implemented as instances of String
class, you can use several methods and properties of this class.
length
property - returns the length of character sequence of an string.compareTo
function - compares this String (object) with the specified object. Returns 0 if the object is equal to the specfied object.get
function - returns character at the specified index.
You can use index access operator instead ofget
function as index access operator internally callsget
function.plus
function - returns a new string which is obtained by the concatenation of this string and the string passed to this function.
You can use+
operator instead ofplus
function as+
operator callsplus
function under the hood.subSequence
Function - returns a new character sequence starting at the specified start and end index.
Example: String Properties and Function
fun main(args: Array) ( val s1 = "Hey there!" val s2 = "Hey there!" var result: String println("Length of s1 string is $(s1.length).") result = if (s1.compareTo(s2) == 0) "equal" else "not equal" println("Strings s1 and s2 are $result.") // s1.get(2) is equivalent to s1(2) println("Third character is $(s1.get(2)).") result = s1.plus(" How are you?") // result = s1 + " How are you?" println("result = $result") println("Substring is "$(s1.subSequence(4, 7)) "") )
When you run the program, the output is:
La lunghezza della stringa s1 è 10. Le stringhe s1 e s2 sono uguali. Il terzo carattere è y. risultato = Hey there! Come stai? La sottostringa è "il"
Visita la classe String Kotlin per ulteriori informazioni su proprietà, estensioni, funzioni e costruttori di estensioni.