String Kotlin e modelos de string (com exemplos)

Neste artigo, você aprenderá sobre strings Kotlin, modelos de string e algumas propriedades e funções de string comumente usadas com a ajuda de exemplos.

String Kotlin

Strings são uma sequência de caracteres. Por exemplo, "Hello there!"é um literal de string.

Em Kotlin, todas as strings são objetos de Stringclasse. Ou seja, literais de string como "Hello there!"são implementados como instâncias desta classe.

Como criar uma variável String?

Aqui está como você pode definir uma Stringvariável em Kotlin. Por exemplo,

 val myString = "Olá!"

Aqui, myString é uma variável do tipo String.

Você pode declarar a variável do tipo Stringe especificar seu tipo em uma instrução e inicializar a variável em outra instrução posteriormente no programa.

 val myString: String… myString = "Olá"

Como acessar os caracteres de uma String?

Para acessar os elementos (caractere) de uma string, o operador de acesso de índice é usado. Por exemplo,

val myString = "Olá!" val item = myString (2)

Aqui, a variável de item contém y, o terceiro caractere da string myString. É porque a indexação em Kotlin começa de 0, não de 1.

val myString = "Olá!" var item: Char item = myString (0) // item contém 'H' item = myString (9) // item contém '!' item = myString (10) // Erro! O índice da string está fora do intervalo item = myString (-1) // Erro! O índice da string está fora do intervalo

Exemplo: iterar por meio de uma string

Se você precisar iterar pelos elementos de uma string, pode fazer isso facilmente usando um loop for.

 fun main(args: Array) ( val myString = "Hey!" for (item in myString) ( println(item) ) )

Quando você executa o programa, a saída será:

 H e y ! 

Strings em Kotlin são imutáveis

Como Java, as strings são imutáveis ​​em Kotlin. Isso significa que você não pode alterar o caractere individual de uma string. Por exemplo,

var myString = "Ei!" myString (0) = 'h' // Erro! Cordas

No entanto, você pode reatribuir uma variável de string novamente se você declarou a variável usando a palavra-chave var. ( Leitura recomendada : Kotlin var Vs val)

Exemplo: reatribuindo uma variável de string.

 fun main(args: Array) ( var myString = "Hey!" println("myString = $myString") myString = "Hello!" println("myString = $myString") )

Quando você executa o programa, a saída será:

myString = Ei! myString = Olá!

Literais de string

Um literal é a representação do código-fonte de um valor fixo. Por exemplo, "Hey there!"é um literal de string que aparece diretamente em um programa sem exigir computação (como variáveis).

Existem dois tipos de literais de string em Kotlin:

1. Cadeia de escape

Uma string de escape pode conter caracteres de escape. Por exemplo,

 val myString = "Olá! n" 

Aqui, é um caractere de escape que insere uma nova linha no texto onde aparece.

Aqui está uma lista de caracteres de escape compatíveis com Kotlin:

  • - guia Inserções
  •  - Insere backspace
  • - Insere nova linha
  • - Insere retorno de carro
  • \' - Insere um caractere de aspas simples
  • " - Insere aspas duplas
  • \ - Insere barra invertida
  • $ - Insere o caractere de dólar

2. String bruta

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 of get function as index access operator internally calls get 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 of plus function as + operator calls plus 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:

O comprimento da string s1 é 10. As strings s1 e s2 são iguais. O terceiro personagem é y. resultado = Olá! Como você está? Substring é "o"

Visite a classe Kotlin String para obter mais informações sobre propriedades de extensão, extensão, funções e construtores.

Artigos interessantes...