• TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • Kotlin Java
  • Kotlin Tutorial
  • Setup Kotlin(Java) Project
  • Kotlin Example Program
  • Convert Java file to Kotlin
  • main() function
  • Kotlin – For Loop
  • Kotlin – While Loop
  • Kotlin – Do-while Loop
  • Kotlin – break
  • Kotlin – continue
  • Kotlin – For i in range
  • Kotlin – Infinite While loop
  • Kotlin Ranges
  • Array Basics
  • Kotlin – Create Array
  • Kotlin – Create Empty Array
  • Kotlin – Create Integer Array
  • Kotlin – Create String Array
  • Kotlin – Create Byte Array
  • Kotlin – Array of Arrays
  • Kotlin – Get Array Size
  • Kotlin – Get Element of Array at Specific Index
  • Kotlin – Set Element of Array at Specific Index
  • Kotlin – Get First Element of Array
  • Kotlin – Get Last Element of Array
  • Kotlin – Print Array in Single Line
  • Array Checks
  • Kotlin – Check if Array is Empty
  • Kotlin – Check if Array Contains Specified Element
  • Array Loops
  • Kotlin – Iterate over Array
  • Kotlin – Array For Loop
  • Kotlin – Array While Loop
  • Array Sorting
  • Kotlin – Array Sorting
  • Kotlin – Sort Array of Integers
  • Kotlin – Sort Array of Strings
  • Kotlin – Sort Array of Strings based on Length
  • Kotlin – Sort Array in Descending Order
  • Kotlin – Classes and Constructors
  • Kotlin – Sealed Class
  • Kotlin – Data Class
  • Kotlin – Enum
  • Kotlin – Extension Functions
  • Inheritance
  • Kotlin – Inheritance
  • Kotlin – Override Method of Super Class
  • Abstraction
  • Kotlin – Abstraction
  • Kotlin – Abstract Class
  • Kotlin – Interfaces
  • Kotlin Try Catch
  • Kotlin – Throw Exception
  • Kotlin – Create custom Exception
  • Kotlin – Initialize string
  • Kotlin – Create empty string
  • Kotlin – Define a string constant
  • Kotlin – Get string length
  • Kotlin – Print a string
  • Kotlin – Concatenate strings
  • Kotlin – Compare strings
  • Kotlin – Multiline strings
  • Kotlin – Check if strings are equal
  • Kotlin – Check if strings are equal ignoring case
  • Kotlin – Check if string is empty
  • Kotlin – Check if string contains specific substring
  • Kotlin – Check if string contains specific character
  • Kotlin – Check if string starts with specific prefix
  • Kotlin – Check if string starts with specific character
  • Kotlin – Check if string ends with specific suffix
  • Kotlin – Check if string ends with specific character
  • Kotlin – Check is string matches regular expression
  • Kotlin – Count number of words in string
  • Kotlin – Find index of substring
  • Kotlin – Get random character from string
  • Kotlin – Substring
  • Transformations
  • Kotlin – Capitalize a string
  • Kotlin – Convert string to lowercase
  • Kotlin – Convert string to uppercase
  • Kotlin – Filter characters of string
  • Kotlin – Join strings by a separator
  • Kotlin – Remove first N characters from string
  • Kotlin – Remove last N haracters from string
  • Kotlin – Repeat string N times
  • Kotlin – Reverse a string
  • Kotlin – Sort characters in string
  • Kotlin – String replace
  • Kotlin – Trim white spaces around string
  • Split Operations
  • Kotlin – Split string
  • Kotlin – Split string to lines
  • Kotlin – Split string by comma
  • Kotlin – Split string by single space
  • Kotlin – Split string by any whitespace character
  • Kotlin – Split string by one or more spaces
  • Conversions
  • Kotlin – Convert char array to string
  • Kotlin – Convert string to char array
  • Kotlin – Convert byte array to string
  • Kotlin – Convert string to byte array
  • Kotlin – Convert string to list of characters
  • Kotlin – Convert list of characters to string
  • Kotlin – Convert string to set of characters
  • Character specific Operations
  • Kotlin – Get character at specific index in string
  • Kotlin – Get first character in string
  • Kotlin – Get last character in string
  • Kotlin – Iterate over each character in string
  • Kotlin – Insert character at specific index in string
  • Kotlin – Get unique characters in string
  • Kotlin – Remove character at specific index in string
  • Kotlin – Remove first character in string
  • Kotlin – Remove last character in string
  • Kotlin – Replace specific character with another in a string
  • Kotlin – Remove specific character in a string
  • String Formatting
  • Kotlin – Write variable inside string
  • String Collections
  • Kotlin – List of strings
  • Kotlin String List – Filter based on Length
  • Kotlin – Filter only strings in this list
  • Kotlin List – Filter non-empty strings
  • Kotlin – Create a set of strings
  • Kotlin – Create string array
  • Kotlin – Sort array of strings
  • Kotlin – Sort string array based on string length
  • ADVERTISEMENT
  • Create Operations
  • Kotlin – Create file
  • Kotlin – Create a directory
  • Kotlin – Create directory recursively
  • Get Properties / Meta
  • Kotlin – Get file creation timestamp
  • Kotlin – Get file extension
  • Kotlin – Get file last modified timestamp
  • Kotlin – Get file name
  • Kotlin – Get file size
  • Iterate over files
  • Kotlin – Iterate through all files in a directory
  • File Checks
  • Kotlin – Check if file exists
  • Kotlin – Check if file is readable
  • Kotlin – Check if file is writable
  • Kotlin – Check if directory exists
  • Read Operations
  • Kotlin – Read file
  • Kotlin – Read file as list of lines
  • Kotlin – Read file character by character
  • Kotlin – Read file line by line
  • Kotlin – Read file into a string
  • Write / Update Operations
  • Kotlin – Append to text file
  • Kotlin – Copy content of a file to another file
  • Kotlin – Copy directory
  • Kotlin – Copy file
  • Kotlin – Move file
  • Kotlin – Move directory
  • Kotlin – Rename file
  • Kotlin – Rename directory
  • Kotlin – Replace specific string in file
  • Kotlin – Write to File
  • Delete Operations
  • Kotlin – Delete a file
  • Kotlin – Delete / remove all content in text file
  • Kotlin – Delete a directory
  • Kotlin - Convert List to Set
  • Kotlin - Create an empty list
  • Kotlin - Filter elements of a List based on Condition
  • Kotlin - Filter even numbers in a list
  • Kotlin - Filter List of strings based on length
  • Kotlin - Filter Odd Numbers in a list
  • Kotlin - Filter only integers in a list
  • Kotlin - Filter only non-empty strings of a list
  • Kotlin - Filter only strings from a list
  • Kotlin - Iterate over Elements of List using For Loop in Kotlin?
  • HKotlin - Iterate over List of Lists
  • Kotlin - Remove all occurrences of element in a list
  • Kotlin - Remove all Elements from a List
  • Kotlin - Remove specific Element in list
  • Kotlin - Access index of element in a list while filtering
  • Kotlin - Add element to List at specific index
  • Kotlin - Add Element to List
  • Kotlin - Define a List of Integers
  • Kotlin - Define a List of Lists
  • Kotlin - Define a List of strings
  • Kotlin - Read file content as a list of lines
  • Kotlin - Remove element at specific index in list
  • Kotlin - replace an Element at specific Index
  • Kotlin List forEach – Example
  • Kotlin List.all()
  • Kotlin List.any()
  • Kotlin List.component1()
  • Kotlin List.component2()
  • Kotlin List.component3()
  • Kotlin List.component4()
  • Kotlin List.component5()
  • Kotlin List.contains()
  • Kotlin List.containsAll()
  • Kotlin List.count()
  • Kotlin List.get()
  • Kotlin List.indexOf()
  • Kotlin List.indices Property
  • Kotlin List.isEmpty()
  • Kotlin List.iterator()
  • Kotlin List.lastIndex
  • Kotlin List.lastIndexOf()
  • Kotlin List.size
  • Kotlin List.subList()
  • Kotlin Mutable List
  • Kotlin – Add two numbers
  • Kotlin – Armstrong number
  • Kotlin – Average of two numbers
  • Kotlin – Average of numbers given in array
  • Kotlin – Check if given number is part of Fibonacci series
  • Kotlin – Check prime number
  • Kotlin – Even number
  • Kotlin – Factorial
  • Kotlin – Factors of a number
  • Kotlin – Fibonacci series
  • Kotlin – Find largest of two numbers
  • Kotlin – Find smallest of two numbers
  • Kotlin – Find largest of three numbers
  • Kotlin – Find smallest of three numbers
  • Kotlin – Odd number
  • Kotlin – Palindrome
  • Kotlin – Print prime numbers
  • Kotlin – Product of digits in a number
  • Kotlin – Reverse a number
  • Kotlin – Sum of first n natural numbers
  • Kotlin – Sum of squares of first n natural numbers
  • Kotlin – Sum of digits in a number
  • Kotlin Interview Questions

Related Tutorials

  • Kotlin Android Tutorial
  • How to Learn Programming
  • ❯ Kotlin Tutorial
  • ❯ Kotlin String Operations
  • ❯ Kotlin – Create a set of strings

How to create a Set of Strings in Kotlin?

In this tutorial, you shall learn how to create a Set of Strings in Kotlin using setOf() or mutableSetOf() functions, with examples.

Kotlin – Create a Set of Strings

To create a Set of Strings in Kotlin, call setOf() function, and pass the String elements to this function. setOf() returns an immutable Set created with the elements passed to it. To create an Mutable Set, use mutableSetOf() function.

In this tutorial, we will learn how to create a Set of Strings using setOf() and mutableSetOf() functions.

1. Create set of string elements

In the following example, we will use setOf() function and create a Set of Strings. We shall pass the elements: “abc”, “xyz”, “pqr”; to the setOf() function.

Since, we are passing the String values to setOf() function, no explicit declaration of the variable as Set<String> or setOf<String>() is required. If we are creating an empty Set of Strings, then we must specify the type of elements we store in this Set.

1. Create a mutable set of string elements

Now, let an create a Mutable Set of Strings using mutableSetOf() function.

In this Kotlin Tutorial , we learned how to create a Set of Strings in Kotlin, using setOf() or mutableSetOf() functions, with the help of examples.

  • How to Convert List to Set in Kotlin?
  • How to Filter Elements of a Set based on Condition in Kotlin?
  • How to Iterate over Elements of Set in Kotlin?
  • How to add an Element to Set in Kotlin?
  • How to check if given Element is present in Set in Kotlin?
  • How to create a Set of Integers in Kotlin?
  • How to create an Empty Set in Kotlin?
  • How to get the Size of Set in Kotlin?
  • Setup of Kotlin Java Project in IntelliJ IDEA

Popular Courses by TutorialKart

App developement, web development, online tools.

Ace your Coding Interview

  • DSA Problems
  • Binary Tree
  • Binary Search Tree
  • Dynamic Programming
  • Divide and Conquer
  • Linked List
  • Backtracking

Initialize a set in Kotlin

This article explores different ways to initialize a set in Kotlin.

1. Using Copy Constructor

You can initialize a set with elements of another collection. The idea is to use a copy constructor that accepts another collection. Note that any duplicates in the list will be silently discarded.

Download Code

2. Using toSet() function

Alternatively, you can call the toSet() function that accumulates the input elements into an unmodifiable instance of Set.

  It can be called upon another collection or an array. Here’s an example using a list:

  If you need a mutable instance of a set, you can use the toMutableSet() function.

3. Using setOf() function

Kotlin provides a convenient way to create instances of Set with small numbers of elements with setOf() function. The setOf() function creates an immutable instance of Set, while mutableSetOf() function creates a mutable instance of it.

4. Using addAll() function

You can initialize a MutableSet later with all elements of a collection or an array using the addAll() function.

5. Using Double Brace Initialization

Although not recommended, you can use Double Brace Initialization in Kotlin, which creates an anonymous inner class with just an instance initializer in it.

That’s all about initializing a set in Kotlin.

Merge two sets in Kotlin
Convert an array to a set in Kotlin
Convert a Set to a List in Kotlin

Rate this post

Average rating 5 /5. Vote count: 20

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and support our growth. Happy coding :)

string set kotlin

Software Engineer | Content Writer | 12+ years experience

guest

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, kotlin introduction.

  • Kotlin Hello World - Your First Kotlin Program
  • Kotlin Comments

Kotlin Fundamentals

  • Kotlin Variables and Basic Types
  • Kotlin Type Conversion
  • Kotlin Operators: Arithmetic, Assignment Operator and More

Kotlin Expression, Statements and Blocks

  • Kotlin Basic Input/Output

Kotlin Flow Control

  • Kotlin if...else Expression
  • Kotlin when Expression
  • Kotlin while and do...while Loop

Kotlin for Loop

  • Kotlin break
  • Kotlin continue

Kotlin Functions

  • Kotlin Function (With Example)
  • Kotlin Function Call Using Infix Notation
  • Kotlin Default and Named Arguments
  • Kotlin Recursion and Tail Recursive Function
  • Kotlin Class and Objects
  • Kotlin Constructors and Initializers
  • Kotlin Getters and Setters (With Example)
  • Kotlin Inheritance
  • Kotlin Visibility Modifiers
  • Kotlin Abstract Class and Abstract Members
  • Kotlin Interfaces
  • Kotlin Nested and Inner Class
  • Kotlin Data Class
  • Kotlin Sealed Classes
  • Kotlin Object Declarations and Expressions
  • Kotlin Companion Objects

Kotlin Extension Function

  • Kotlin Operator Overloading

Additional Topics

  • Kotlin Keywords and Identifiers

Kotlin String and String Templates

  • Kotlin Lambdas
  • Kotlin Bitwise and Bitshift Operations

Kotlin Tutorials

  • Check Whether a Character is Alphabet or Not
  • Find ASCII value of a character

Kotlin if Expression

Kotlin String

Strings are a sequence of characters. For example, "Hello there!" is a string literal.

In Kotlin, all strings are objects of String class. Meaning, string literals such as  "Hello there!"  are implemented as instances of this class. 

How to create a String variable?

Here is how you can define a String variable in Kotlin. For example,

Here, myString is a variable of type String .

You can declare variable of type String and specify its type in one statement, and initialize the variable in another statement later in the program.

  • How to access characters of a String?

To access elements (character) of a string, index access operator is used. For example,

Here, item variable contains y , third character of the myString string. It's because indexing in Kotlin starts from 0 not 1.

Example: Iterate through a String

If you need to iterate through elements of a string, you can do it easily by using a for loop .

When you run the program, the output will be:

  • Strings in Kotlin are Immutable

Like Java, strings are immutable in Kotlin. This means, you cannot change individual character of a string. For example,

However, you can reassign a string variable again if you declared the variable using keyword var . ( Recommended Reading : Kotlin var Vs val )

Example: Reassigning a String Variable.

  • String Literals

A literal is the source code representation of a fixed value. For example, "Hey there!" is a string literal that appears directly in a program without requiring computation (like variables ).

There are two types of string literals in Kotlin:

1. Escaped string

A escaped string may have escaped characters in them. For example,

Here, \n is an escape character which inserts a newline in the text where it appears.

Here is a list of escape characters supported in Kotlin:

  • \t - Inserts tab
  • \b - Inserts backspace
  • \n - Inserts newline
  • \r - Inserts carriage return
  • \' - Inserts single quote character
  • \" - Inserts double quote character
  • \\ - Inserts backslash
  • \$ - Inserts dollar character

2. Raw String

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,

You can remove the leading whitespaces of a raw string using trimMargin() function . For example,

  • Example: Printing Raw String

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

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

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

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

When you run the program, the output is:

Visit Kotlin String class for more information on extension properties, extension, functions and constructors.

Table of Contents

  • How to define a String variable?
  • Example: Iterate Through a String
  • Example: Reassigning a String Variable
  • Commonly Used String Properties and Functions

Sorry about that.

Related Tutorials

Kotlin Tutorial

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Kotlin string

last modified January 29, 2024

In this article we show how to work with strings in Kotlin.

A string is a basic data type in a programming language. In Kotlin, the String class represents character strings. Kotlin string literals are implemented as instances of this class. Kotlin uses double quotes to create string literals.

Kotlin has a rich API for working with strings. It contains plenty of methods for various string operations. Kotlin/Java strings are immutable, which means that all modification operations create new string instead of modifying a string in-place.

Kotlin string example

In the first example, we have a simple Kotlin string example.

The example creates a string, uses a string concatenation operation, and determines the width of the string.

A string literal is created and passed to the s variable. The string is printed to the console with println .

In Kotlin, strings are concatenated with the + operator.

The length of a string is determined with the length attribute.

Kotlin string length

For many alphabets, the length property gives the correct number of characters.

In the example, we print the number of characters for English, Slovak, Russian, and Japanese words.

The output is correct.

However, there are alphabets for which the length property gives incorrect output.

For instance, for emojis and Sanskrit words, the length property gives wrong numbers. We can get the correct answer for emojis with BreakIterator . However, for the Sanskrit word, the BreakIterator is still incorrect.

There are 10 emoji characters and 4 Sanskrit characters.

Kotlin string indexing

A string is a sequence of characters. We can get specific characters from a string with indexing operations.

The example shows how to get the first and last characters of a string. It uses indexing operations and alternative string methods.

The indexes start from zero; therefore, the first character has zero index. The index of the character is placed between square brackets.

The first method returns the first and the last returns the last character of the string.

Kotlin string interpolation

String interpolation is variable substitution with its value inside a string. In Kotlin, we use the $ character to interpolate a variable and ${} to interpolate an expression.

Kotlin string formatting is more powerful than basic interpolation.

The example shows how to do string interpolation in Kotlin.

We have two variables.

The two variables are interpolated within the string; i.e. they are substituted with their values.

Here we get the length of the string. Since it is an expression, we need to put it inside the {} brackets.

Kotlin comparing strings

We can use the == operator and the compareTo method to compare string content.

In the example, we compare two strings.

The == operator compares structural equality, that is, the content of the two strings.

The compareTo method compares two strings lexicographically, optionally ignoring case.

Kotlin string escape characters

The string escaping characters are special characters that perform a specific operation. For instance, the \n characters starts a new line.

The example presents the character escaping in Kotlin.

We insert double qoutes into a string literal by escaping the original function of double quotes.

With \n , we create three lines.

Kotlin string case

Kotlin has methods for working with the case of a string characters.

The example presents four methods: capitalize , toUpperCase , toLowerCase , and decapitalize .

Kotlin empty/blank string

Kotlin distinguishes between empty and blank strings. An empty string does not have any characters, a blank string contains any number of white spaces.

The example tests if a string is bland and empty.

The isEmpty returns true if the string is empty.

The isBlank returns true if the string is blank.

Kotlin string white space stripping

We often need to strip white space characters from a string.

The example presents methods for stripping white spaces from a string.

The trimEnd method removes trailing white spaces.

The trimStart method removes leading white spaces.

The trim method removes both trailing and leading white spaces.

Kotlin string looping

A Kotlin string is a sequence of characters. We can loop this sequence.

The example loops over a string using a for loop, forEach loop, and forEachIndexed loop.

We traverse the string with a for loop and print each of the characters.

We traverse over a loop with forEach and print a byte value of each of the characters.

With forEachIndexed, we print the character with its index.

Kotlin string filtering

The filter method returns a string containing only those characters from the original string that match the given predicate.

The example counts all vowels in the string.

We create an extension function; it returns true for English vowels.

The extension function is called in the filter method.

Kotlin string startsWith/endsWith

The startsWith method returns true if a string starts with the specified prefix and the endsWith returns true if a string ends with the specified character.

In the example, we have a list of words. With the aforementioned methods we find out which words start with 't' and and with 'k'.

With listOf , we define a list of words.

We call two custom funcions in the filter method.

The startWithT is a custom predicate function which returns true if a string starts with 't'.

Kotlin string replace

The replace method returns a new string obtained by replacing all occurrences of the old string with a new string.

The example replaces sunny with rainy. A new modified string is returned. The original string is not modified.

Kotlin string split

The split function cuts the string into a list of strings based on the specified delimiter.

We have a string consisting of birds delimited by comma. We split the strings to get all birds separately.

Kotlin toString

The toString method is called when the object is used in a string context; e.g. it is printed to the console. Its purpose is to provide a string representation of the object.

The example creates a list of city objects. We go through the list and print the objects to the console.

We override the default implementation of toString . It returns a string that a city has the specified population.

Kotlin raw string

A raw string is delimited by triple quotes """. It does no escaping and can contain newlines and any other characters.

In the example we have a multi-line string, which contains a verse. We strip the indent when the string is printed.

Kotlin string padding

Kotlin has methods for padding strings with a specified character or space.

The example pads numbers with a dot character using padStart .

Kotlin String - language reference

In this article we have covered Kotlin strings.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Kotlin tutorials .

string set kotlin

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt
  • Android Developers

String resources

A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings:

All strings are capable of applying some styling markup and formatting arguments. For information about styling and formatting strings, see the section about Formatting and Styling .

A single string that can be referenced from the application or from other resource files (such as an XML layout).

Note: A string is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). So, you can combine string resources with other simple resources in the one XML file, under one <resources> element.

No attributes.

attributes:

This layout XML applies a string to a View:

This application code retrieves a string:

You can use either getString(int) or getText(int) to retrieve a string. getText(int) retains any rich text styling applied to the string.

String array

An array of strings that can be referenced from the application.

Note: A string array is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine string array resources with other simple resources in the one XML file, under one <resources> element.

This application code retrieves a string array:

Quantity strings (plurals)

Note: A plurals collection is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine plurals resources with other simple resources in the one XML file, under one <resources> element.

XML file saved at res/values-pl/strings.xml :

When using the getQuantityString() method, you need to pass the count twice if your string includes string formatting with a number. For example, for the string %d songs found , the first count parameter selects the appropriate plural string and the second count parameter is inserted into the %d placeholder. If your plural strings do not include string formatting, you don't need to pass the third parameter to getQuantityString .

Format and style

Here are a few important things you should know about how to properly format and style your string resources.

Handle special characters

When a string contains characters that have special usage in XML, you must escape the characters according to the standard XML/HTML escaping rules. If you need to escape a character that has special meaning in Android you should use a preceding backslash.

By default Android will collapse sequences of whitespace characters into a single space. You can avoid this by enclosing the relevant part of your string in double quotes. In this case all whitespace characters (including new lines) will get preserved within the quoted region. Double quotes will allow you to use regular single unescaped quotes as well.

Whitespace collapsing and Android escaping happens after your resource file gets parsed as XML. This means that <string> &#32; &#8200; &#8195;</string> (space, punctuation space, Unicode Em space) all collapse to a single space ( " " ), because they are all Unicode spaces after the file is parsed as an XML. To preserve those spaces as they are, you can either quote them ( <string>" &#32; &#8200; &#8195;"</string> ) or use Android escaping ( <string> \u0032 \u8200 \u8195</string> ).

Note: From XML parser's perspective, there is no difference between <string>"Test this"</string> and <string>&quot;Test this&quot;</string> whatsoever. Both forms will not show any quotes but trigger Android whitespace-preserving quoting (that will have no practical effect in this case).

Formatting strings

If you need to format your strings, then you can do so by putting your format arguments in the string resource, as demonstrated by the following example resource.

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. Then, format the string by calling getString(int, Object...) . For example:

Styling with HTML markup

You can add styling to your strings with HTML markup. For example:

The following HTML elements are supported:

  • Bold: <b>
  • Italic: <i>, <cite>, <dfn>, <em>
  • 25% larger text: <big>
  • 20% smaller text: <small>
  • Setting font properties: <font face=”font_family“ color=”hex_color”>. Examples of possible font families include monospace , serif , and sans_serif .
  • Setting a monospace font family: <tt>
  • Strikethrough: <s>, <strike>, <del>
  • Underline: <u>
  • Superscript: <sup>
  • Subscript: <sub>
  • Bullet points: <ul>, <li>
  • Line breaks: <br>
  • Division: <div>
  • CSS style: <span style=”color|background_color|text-decoration”>
  • Paragraphs: <p dir=”rtl | ltr” style=”…”>

If you aren't applying formatting, you can set TextView text directly by calling setText(java.lang.CharSequence) . In some cases, however, you may want to create a styled text resource that is also used as a format string. Normally, this doesn't work because the format(String, Object...) and getString(int, Object...) methods strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String) , after the formatting takes place. For example:

In this formatted string, a <b> element is added. Notice that the opening bracket is HTML-escaped, using the &lt; notation.

Because the fromHtml(String) method formats all HTML entities, be sure to escape any possible HTML characters in the strings you use with the formatted text, using htmlEncode(String) . For instance, if you are formatting a string that contains characters such as "<" or "&", then they must be escaped before formatting, so that when the formatted string is passed through fromHtml(String) , the characters come out the way they were originally written. For example:

Styling with spannables

A Spannable is a text object that you can style with typeface properties such as color and font weight. You use SpannableStringBuilder to build your text and then apply styles defined in the android.text.style package to the text.

You can use the following helper methods to set up much of the work of creating spannable text:

The following bold , italic , and color methods wrap the helper methods above and demonstrate specific examples of applying styles defined in the android.text.style package. You can create similar methods to do other types of text styling.

Here's an example of how to chain these methods together to apply various styles to individual words within a phrase:

The core-ktx Kotlin module also contains extension functions that make working with spans even easier. You can check out the android.text package documentation on GitHub to learn more.

For more information on working with spans, see the following links:

  • Spantastic text styling with Spans
  • Understanding spans

Styling with annotations

You can apply complex or custom styling by using the Annotation class along with the <annotation> tag in your strings.xml resource files. The annotation tag allows you to mark parts of the string for custom styling by defining custom key-value pairs in the XML that the framework then converts into Annotation spans. You can then retrieve these annotations and use the key and value to apply the styling.

When creating annotations, make sure you add the <annotation> tag to all translations of the string in every strings.xml file.

string set kotlin

Example - adding a custom typeface

Add the <annotation> tag, and define the key-value pair. In this case, the key is font , and the value is the type of font we want to use: title_emphasis

Load the string resource and find the annotations with the font key. Then create a custom span and replace the existing span.

If you’re using the same text multiple times, you should construct the SpannableString object once and reuse it as needed to avoid potential performance and memory issues.

For more examples of annotation usage, see Styling internationalized text in Android

Annotation spans and text parceling

Because Annotation spans are also ParcelableSpans , the key-value pairs are parceled and unparceled. As long as the receiver of the parcel knows how to interpret the annotations, you can use Annotation spans to apply custom styling to the parceled text.

To keep your custom styling when you pass the text to an Intent Bundle, you first need to add Annotation spans to your text. You can do this in the XML resources via the <annotation> tag, as shown in the example above, or in code by creating a new Annotation and setting it as a span, as shown below:

Retrieve the text from the Bundle as a SpannableString and then parse the annotations attached, as shown in the example above.

For more information on text styling, see the following links:

  • Google I/O 2018 talk - Best practices for text on Android

Content and code samples on this page are subject to the licenses described in the Content License . Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2024-01-03 UTC.

Kotlin Help

Declaring properties.

Properties in Kotlin classes can be declared either as mutable, using the var keyword, or as read-only, using the val keyword.

To use a property, simply refer to it by its name:

Getters and setters

The full syntax for declaring a property is as follows:

The initializer, getter, and setter are optional. The property type is optional if it can be inferred from the initializer or the getter's return type, as shown below:

The full syntax of a read-only property declaration differs from a mutable one in two ways: it starts with val instead of var and does not allow a setter:

You can define custom accessors for a property. If you define a custom getter, it will be called every time you access the property (this way you can implement a computed property). Here's an example of a custom getter:

You can omit the property type if it can be inferred from the getter:

If you define a custom setter, it will be called every time you assign a value to the property, except its initialization. A custom setter looks like this:

By convention, the name of the setter parameter is value , but you can choose a different name if you prefer.

If you need to annotate an accessor or change its visibility, but you don't want to change the default implementation, you can define the accessor without defining its body:

Backing fields

In Kotlin, a field is only used as a part of a property to hold its value in memory. Fields cannot be declared directly. However, when a property needs a backing field, Kotlin provides it automatically. This backing field can be referenced in the accessors using the field identifier:

The field identifier can only be used in the accessors of the property.

A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier.

For example, there would be no backing field in the following case:

Backing properties

If you want to do something that does not fit into this implicit backing field scheme, you can always fall back to having a backing property :

Compile-time constants

If the value of a read-only property is known at compile time, mark it as a compile time constant using the const modifier. Such a property needs to fulfil the following requirements:

It must be a top-level property, or a member of an object declaration or a companion object .

It must be initialized with a value of type String or a primitive type

It cannot be a custom getter

The compiler will inline usages of the constant, replacing the reference to the constant with its actual value. However, the field will not be removed and therefore can be interacted with using reflection .

Such properties can also be used in annotations:

Late-initialized properties and variables

Normally, properties declared as having a non-nullable type must be initialized in the constructor. However, it is often the case that doing so is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In these cases, you cannot supply a non-nullable initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

To handle such cases, you can mark the property with the lateinit modifier:

This modifier can be used on var properties declared inside the body of a class (not in the primary constructor, and only when the property does not have a custom getter or setter), as well as for top-level properties and local variables. The type of the property or variable must be non-nullable, and it must not be a primitive type.

Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.

Checking whether a lateinit var is initialized

To check whether a lateinit var has already been initialized, use .isInitialized on the reference to that property :

This check is only available for properties that are lexically accessible when declared in the same type, in one of the outer types, or at top level in the same file.

Overriding properties

See Overriding properties

Delegated properties

The most common kind of property simply reads from (and maybe writes to) a backing field, but custom getters and setters allow you to use properties so one can implement any sort of behavior of a property. Somewhere in between the simplicity of the first kind and variety of the second, there are common patterns for what properties can do. A few examples: lazy values, reading from a map by a given key, accessing a database, notifying a listener on access.

Such common behaviors can be implemented as libraries using delegated properties .

IMAGES

  1. Kotlin String

    string set kotlin

  2. Kotlin String Format Example

    string set kotlin

  3. How to Use the Set Interface in Kotlin

    string set kotlin

  4. The Complete Kotlin Course #9

    string set kotlin

  5. Kotlin tutorial : String in Kotlin with examples

    string set kotlin

  6. Kotlin String

    string set kotlin

VIDEO

  1. CS 124 Kotlin String.toInt Exceptions

  2. 008 Kotlin Variable type String

  3. Kotlin Strings Basics

  4. #7 Kotlin : String Comparison in Kotlin

  5. How to convert String to Int in Kotlin

  6. Kotlin Tutorial

COMMENTS

  1. How to create a Set of Strings in Kotlin?

    Kotlin - Create a Set of Strings. To create a Set of Strings in Kotlin, call setOf () function, and pass the String elements to this function. setOf () returns an immutable Set created with the elements passed to it. To create an Mutable Set, use mutableSetOf () function.

  2. Guide to Set and MutableSet in Kotlin

    Even though the set data structure is immutable in Kotlin, we can perform the set operations, such as intersection, union, and so on, to produce a new set that contains the resultant set. Let's start by defining two immutable sets of numbers, namely, setA and setB: val setA = setOf( 1, 2, 3 ) val setB = setOf( 3, 4, 5) Now, let's use the ...

  3. Set

    Returns a set containing all elements of the original set and the given elements sequence, which aren't already in this set. operator fun <T> Set<T>.plus(elements: Sequence<T>): Set<T>. Returns a list containing all elements of the original collection and then the given element.

  4. Strings

    Strings in Kotlin are represented by the type String. On the JVM, an object of String type in UTF-16 encoding uses approximately 2 bytes per character. Generally, a string value is a sequence of characters in double quotes ( " ): Elements of a string are characters that you can access via the indexing operation: s[i].

  5. Kotlin set

    In this article we show how to work with sets in Kotlin. A set is a generic unordered collection of elements which allows no duplicates. Kotlin distinguishes between read-only and mutable sets. Read-only sets are created with setOf and mutable set with mutableSetOf. Kotlin setOf. The setOf method creates a new read-only set in Kotlin.

  6. Kotlin

    As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format()) See Kotlin's documentation. Your code would be: val pi = 3.14159265358979323. val s = "pi = %.2f".format(pi)

  7. Initialize a set in Kotlin

    This article explores different ways to initialize a set in Kotlin. 1. Using Copy Constructor. You can initialize a set with elements of another collection. The idea is to use a copy constructor that accepts another collection. Note that any duplicates in the list will be silently discarded. 2. Using toSet() function.

  8. Collections overview

    The Kotlin Standard Library provides a comprehensive set of tools for managing collections - groups of a variable number of items (possibly zero) that are significant to the problem being solved and are commonly operated on.. Collections are a common concept for most programming languages, so if you're familiar with, for example, Java or Python collections, you can skip this introduction and ...

  9. Kotlin String and String Templates (With Examples)

    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.

  10. Kotlin string

    In Kotlin, the String class represents character strings. Kotlin string literals are implemented as instances of this class. Kotlin uses double quotes to create string literals. Kotlin has a rich API for working with strings. It contains plenty of methods for various string operations. Kotlin/Java strings are immutable, which means that all ...

  11. String resources

    You can use either getString(int) or getText(int) to retrieve a string. getText(int) retains any rich text styling applied to the string. String array. An array of strings that can be referenced from the application. Note: A string array is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine string array ...

  12. Kotlin String Templates

    In Kotlin, additionally, we have triple-quoted raw Strings that can contain special characters without the need for escaping them. The resulting String is contained between two consecutive non-overlapping occurrences of triple double-quote-signs ".. For example, in Java, in order to create properly a String containing a Windows-style file path to a resource located at C:\Repository\read.me ...

  13. stringSetOf

    stringSetOf. JS. 1.1. fun stringSetOf(vararg elements: String): HashSet<String>. (source) Creates a new instance of the specialized implementation of HashSet with the specified String elements, which elements the keys as properties of JS object without hashing them.

  14. Functions for Replacing Part of a String in Kotlin

    6.1. Numerical Range. In order to replace a range of characters, we can use the replaceRange (startIndex, endIndex, replacement) extension function: val txt = "42 is the answer" val replaced = txt.replaceRange(0, 3, "") assertEquals("is the answer", replaced) Copy. As usual, the startIndex is inclusive, and the endIndex is exclusive.

  15. Concatenate Strings in Kotlin

    The simplest way of concatenating Strings in Kotlin is to use the + operator. As a result, we get a new String object composed of Strings on the left and the right side of the operator: val a = "Hello" val b = "Baeldung" val c = a + " " + b. assertEquals("Hello Baeldung", c) Another key point is that in Kotlin, thanks to operator overload, the ...

  16. String

    1.0. fun String(. bytes: ByteArray, offset: Int, length: Int, charset: Charset. ): String. (source) Converts the data from a portion of the specified array of bytes to characters using the specified character set and returns the conversion result as a string.

  17. What's the Kotlin equivalent of Java's String[]?

    There's no special case for String, because String is an ordinary referential type on JVM, in contrast with Java primitives (int, double, ...)-- storing them in a reference Array<T> requires boxing them into objects like Integer and Double.The purpose of specialized arrays like IntArray in Kotlin is to store non-boxed primitives, getting rid of boxing and unboxing overhead (the same as Java ...

  18. Properties

    var setterVisibility: String = "abc" private set // the setter is private and has the default implementation var setterWithAnnotation: Any? = null @Inject set // annotate the setter with Inject ... In Kotlin, a field is only used as a part of a property to hold its value in memory. Fields cannot be declared directly. However, when a property ...

  19. android

    Answer found, in the next activity, you have to do this to get the string: val ss:String = intent.getStringExtra("samplename").toString() edited Jan 15, 2021 at 19:13. SHAH MD IMRAN HOSSAIN. 2,794 2 27 45. answered Jul 16, 2017 at 20:55. zasaz. 2,484 2 16 27.

  20. How to convert String to Int in Kotlin?

    Are you actually sure it's a String, though? If you're iterating over a single String, you don't get instances of String of length 1 (as you might expect if you're used to another language, ie, Python), but instances of Char, in which case you want to use digitToInt() instead: val myInt = myChar.digitToInt()