Kotlin String dan Template String (Dengan Contoh)

Dalam artikel ini, Anda akan belajar tentang string Kotlin, template string, dan beberapa properti dan fungsi string yang umum digunakan dengan bantuan contoh.

Kotlin String

String adalah urutan karakter. Misalnya "Hello there!"adalah string literal.

Di Kotlin, semua string adalah objek Stringkelas. Artinya, string literal seperti "Hello there!"diimplementasikan sebagai instance dari kelas ini.

Bagaimana cara membuat variabel String?

Berikut adalah cara Anda mendefinisikan Stringvariabel di Kotlin. Sebagai contoh,

 val myString = "Hai yang di sana!"

Di sini, myString adalah variabel tipe String.

Anda dapat mendeklarasikan variabel tipe Stringdan menentukan tipenya dalam satu pernyataan, dan menginisialisasi variabel dalam pernyataan lain nanti dalam program.

 val myString: String… myString = "Halo"

Bagaimana cara mengakses karakter String?

Untuk mengakses elemen (karakter) dari sebuah string, digunakan operator akses indeks. Sebagai contoh,

val myString = "Hai yang di sana!" val item = myString (2)

Di sini, variabel item berisi y, karakter ketiga dari string myString. Itu karena pengindeksan di Kotlin dimulai dari 0 bukan 1.

val myString = "Hai yang di sana!" var item: Char item = myString (0) // item berisi 'H' item = myString (9) // item contains '!' item = myString (10) // Error! Indeks string di luar kisaran item = myString (-1) // Error! Indeks string di luar jangkauan

Contoh: Iterasi melalui String

Jika Anda perlu melakukan iterasi melalui elemen string, Anda dapat melakukannya dengan mudah menggunakan for loop.

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

Saat Anda menjalankan program, hasilnya adalah:

 H e y ! 

String di Kotlin tidak dapat diubah

Seperti Java, string tidak dapat diubah di Kotlin. Artinya, Anda tidak dapat mengubah karakter individu dari sebuah string. Sebagai contoh,

var myString = "Hei!" myString (0) = 'h' // Kesalahan! String

Namun, Anda dapat menetapkan kembali variabel string jika Anda mendeklarasikan variabel menggunakan kata kunci var. ( Bacaan yang Disarankan : Kotlin var Vs val)

Contoh: Menetapkan Kembali Variabel String.

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

Saat Anda menjalankan program, hasilnya adalah:

myString = Hei! myString = Halo!

String Literals

Literal adalah representasi kode sumber dari nilai tetap. Misalnya, "Hey there!"adalah string literal yang muncul secara langsung dalam program tanpa memerlukan komputasi (seperti variabel).

Ada dua jenis string literal di Kotlin:

1. String yang lolos

String yang lolos mungkin memiliki karakter yang lolos di dalamnya. Sebagai contoh,

 val myString = "Hai yang di sana! n" 

Di sini, adalah karakter pelarian yang menyisipkan baris baru di teks di mana ia muncul.

Berikut adalah daftar karakter escape yang didukung di Kotlin:

  • - Tab Sisipan
  •  - Menyisipkan backspace
  • - Sisipkan baris baru
  • - Memasukkan carriage return
  • \' - Menyisipkan karakter kutipan tunggal
  • " - Menyisipkan karakter kutip ganda
  • \ - Sisipan garis miring terbalik
  • $ - Menyisipkan karakter dolar

2. String Mentah

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:

Panjang string s1 adalah 10. String s1 dan s2 sama. Karakter ketiga adalah y. result = Halo! Apa kabar? Substring adalah "the"

Kunjungi kelas Kotlin String untuk informasi selengkapnya tentang properti ekstensi, ekstensi, fungsi, dan konstruktor.

Artikel yang menarik...