Contents

Array & String

Arrays

In Kotlin, arrays are used to store multiple elements of the same type in a single variable. Arrays are a fundamental data structure that allows efficient storage and retrieval of data. Kotlin provides various methods and functions to operate on arrays, making them versatile and powerful.

Creating Arrays:

1. Using arrayOf(): This method creates an array of specified elements.

Syntax:

				
					val intArray = arrayOf(1, 2, 3, 4)
val stringArray = arrayOf("one", "two", "three")
				
			

Example

				
					fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)

    // Print all elements
    numbers.forEach { println(it) }

    // Modify and print the array
    numbers[2] = 10
    println(numbers.joinToString())
}

				
			

Output

				
					1
2
3
4
5
1, 2, 10, 4, 5

				
			

2. Using Array Constructor :The constructor takes the size of the array and a lambda function to initialize the elements.

Syntax

				
					 val num = Array(3, {i-> i*1})

				
			

Example

				
					fun main() 
{ 
	val arrayname = Array(5, { i -> i * 1 }) 
	for (i in 0..arrayname.size-1) 
	{ 
		println(arrayname[i]) 
	} 
} 

				
			

Output

				
					0
1
2
3
4
				
			

3. Typed Arrays: Kotlin provides specialized classes for primitive arrays to avoid the overhead of boxing.

Syntax:

				
					    val num = Array(3) { i -> i * 1 }

				
			

Example

				
					fun main() {
    // Creating an IntArray of size 5, initialized with index * 2
    val intArray = IntArray(5) { it * 2 }

    // Creating a DoubleArray of size 3, initialized with index + 0.5
    val doubleArray = DoubleArray(3) { it + 0.5 }

    // Creating a BooleanArray with predefined values
    val booleanArray = booleanArrayOf(true, false, true)

    // Printing the contents of each typed array
    println("IntArray: ${intArray.joinToString()}")
    println("DoubleArray: ${doubleArray.joinToString()}")
    println("BooleanArray: ${booleanArray.joinToString()}")
}

				
			

Output

				
					 1 2 3 4 5
 10 20 30 40 50
				
			
Accessing Array Elements

1. Using indexing : In Kotlin, array elements can be accessed using indexing. This involves specifying the position of the element within the array using its index. Array indices start at 0, so the first element is accessed with index 0, the second with index 1, and so on. Indexing is a straightforward way to retrieve or modify individual elements of an array.

Syntax:

				
					val element = array[index]

				
			

Example

				
					fun main() {
    // Define an array of integers
    val numbers = arrayOf(10, 20, 30, 40, 50)

    // Access elements using indexing
    val firstElement = numbers[0]   // Access the first element
    val secondElement = numbers[1]  // Access the second element
    val lastElement = numbers[4]    // Access the last element

    // Print the accessed elements
    println("First element: $firstElement")
    println("Second element: $secondElement")
    println("Last element: $lastElement")
}

				
			

Output:

				
					First element: 10
Second element: 20
Last element: 50

				
			

2. Modifying Elements: Modifying elements in an array means changing the value of an element at a specific index. In an array, you can update any element by accessing it through its index and assigning a new value to that position. The array’s length and structure remain the same, but the value at the chosen index is replaced.

Syntax:

				
					array[index] = new_value
				
			

Example

				
					fun main() {
    // Define an array
    val arr = arrayOf(5, 10, 15, 20, 25)

    // Modify the element at index 1 (second element)
    arr[1] = 12

    // Modify the last element using a negative-like index (-1 is the last element)
    arr[arr.size - 1] = 30

    // Print the updated array
    println("Updated array: ${arr.joinToString(", ")}")
}

				
			

Output:

				
					Updated array: 5, 12, 15, 20, 30

				
			
Array Methods:

1. Size: In Kotlin, the size property returns the number of elements in an array. This is useful when you want to know how many items are stored in the array. It is not a method but a property that gives you the length of the array.

Syntax:

				
					array.size
				
			

Example

				
					fun main() {
    // Define an array
    val arr = arrayOf(1, 2, 3, 4, 5)

    // Get the size of the array
    val arraySize = arr.size

    // Print the size
    println("The size of the array is: $arraySize")
}

				
			

Output:

				
					The size of the array is: 5
				
			

2. Iterating Over an Array: Iterating over an array refers to accessing each element of the array one by one in sequence. It allows you to perform operations on each element. In Kotlin, this can be done using a for loop or the forEach function, both of which are commonly used to traverse an array.

Syntax:

				
					for (element in array) {
    // Perform an operation with each element
}

				
			

Example

				
					fun main() {
    // Define an array
    val arr = arrayOf(10, 20, 30, 40, 50)

    // Iterate over the array
    for (element in arr) {
        println(element)
    }
}

				
			

Output:

				
					10
20
30
40
50
				
			

3. Using Higher-Order Functions: Higher-order functions in Kotlin are functions that take other functions as parameters or return functions. These are commonly used to perform operations on collections or arrays. Functions like map, filter, forEach, etc., are examples of higher-order functions that allow functional-style processing of array elements.

Syntax:

				
					array.functionName { element -> 
    // Perform an operation with each element
}

				
			

Example

				
					fun main() {
    // Define an array
    val arr = arrayOf(1, 2, 3, 4, 5)

    // Use higher-order function map to create a new array with doubled values
    val doubledArray = arr.map { it * 2 }

    // Print the new array
    println(doubledArray)
}

				
			

Output:

				
					[2, 4, 6, 8, 10]

				
			

Kotlin Strings

Strings in Kotlin are sequences of characters enclosed within double quotes. Strings are immutable, meaning that once a string is created, its value cannot be altered. Kotlin strings come with a rich set of methods for performing operations like concatenation, comparison, searching, and more.

Creating Strings:

1. Literal: Strings can be created by directly assigning a sequence of characters to a variable.

Syntax:

				
					val variableName = "Your string here"
				
			

Example

				
					fun main() {
    // Creating a string literal
    val greeting = "Hello, Kotlin!"

    // Print the string
    println(greeting)
}

				
			

Output:

				
					Hello, Kotlin!
				
			

2. Using String Constructor: In Kotlin, you can create strings using the String constructor, which allows you to create a string from an array of characters. This approach is useful when you have a character array and want to transform it into a string. The String constructor takes a CharArray (array of characters) as a parameter and returns a string.

Syntax:

				
					val stringVariable = String(charArray)
				
			

Example

				
					fun main() {
    // Create a character array
    val charArray = charArrayOf('K', 'o', 't', 'l', 'i', 'n')

    // Use the String constructor to create a string from the character array
    val str = String(charArray)

    // Print the string
    println(str)
}
				
			

Output:

				
					Kotlin
				
			
String Templates:

1. Variable Interpolation: You can embed variables directly within strings using the ${} syntax.

Syntax:

				
					val variable = "value"
val result = "String with $variable inside"
				
			

Example

				
					fun main() {
    // Declare a variable
    val name = "Kotlin"

    // Use string interpolation to include the variable in the string
    val greeting = "Hello, $name!"

    // Print the interpolated string
    println(greeting)
}

				
			

Output:

				
					Hello, Kotlin!

				
			

2. Expression Interpolation: In Kotlin, you can embed expressions inside strings using string templates. This allows you to include the result of any expression within a string, which will be evaluated and concatenated as part of the string. Expressions are enclosed in curly braces ${}.

Syntax:

				
					val result = "String with ${expression} inside"

				
			

Example

				
					fun main() {
    // Declare variables
    val x = 10
    val y = 20

    // Use string interpolation to include an expression in the string
    val result = "The sum of $x and $y is ${x + y}"

    // Print the result
    println(result)
}

				
			

Output:

				
					The sum of 10 and 20 is 30

				
			
String Methods:

1. Length: In Kotlin, you can get the length of a string using the length property. This property returns the number of characters present in the string.

Syntax:

				
					val length = stringVariable.length

				
			

Example

				
					fun main() {
    // Define a string
    val text = "Kotlin Programming"

    // Get the length of the string
    val length = text.length

    // Print the length
    println("The length of the string is: $length")
}

				
			

Output:

				
					The length of the string is: 18

				
			

2. Accessing Characters: In Kotlin, characters in a string can be accessed using their index. Since strings are zero-indexed, the index starts at 0 for the first character. You can use square brackets [] to access individual characters at a specified index.

Syntax:

				
					val character = stringVariable[index]

				
			

Example

				
					fun main() {
    // Define a string
    val text = "Kotlin"

    // Access characters by index
    val firstChar = text[0]    // First character
    val thirdChar = text[2]    // Third character
    val lastChar = text[text.length - 1]  // Last character

    // Print the accessed characters
    println("First character: $firstChar")
    println("Third character: $thirdChar")
    println("Last character: $lastChar")
}

				
			

Output:

				
					First character: K
Third character: t
Last character: n

				
			

3. Substrings: In Kotlin, extract a part of a string using the substring method. This method allows you to specify a range of indices and returns a new string that contains the characters from the starting index up to, but not including, the ending index.

Example

				
					val substring = stringVariable.substring(startIndex)

				
			

Example

				
					fun main() {
    // Define a string
    val text = "Kotlin Programming"

    // Extract substrings
    val firstPart = text.substring(0, 6)    // Extracts "Kotlin"
    val secondPart = text.substring(7)      // Extracts "Programming"

    // Print the substrings
    println("First part: $firstPart")
    println("Second part: $secondPart")
}

				
			

Output:

				
					First part: Kotlin
Second part: Programming

				
			

4. String Comparison: Kotlin provides two types of equality checks for strings:

  • == for structural equality (checks if the values are the same).
  • === for referential equality (checks if the references point to the same object).

Syntax:

				
					Structural Equality: string1 == string2

				
			
				
					Referential Equality: string1 === string2
				
			

Example:

				
					fun main() {
    // Define strings
    val str1 = "Kotlin"
    val str2 = "Kotlin"
    val str3 = str1
    val str4 = String("Kotlin".toCharArray()) // Creates a new String object with the same content

    // Structural equality
    println("str1 == str2: ${str1 == str2}") // True, because the content is the same
    println("str1 == str4: ${str1 == str4}") // True, because the content is the same

    // Referential equality
    println("str1 === str2: ${str1 === str2}") // True, because both refer to the same interned object
    println("str1 === str3: ${str1 === str3}") // True, because str3 is assigned from str1
    println("str1 === str4: ${str1 === str4}") // False, because str4 is a new object, even though it has the same content
}

				
			

Output:

				
					str1 == str2: true
str1 == str4: true
str1 === str2: true
str1 === str3: true
str1 === str4: false

				
			

5. String Manipulation: Kotlin provides several common methods for manipulating strings. These include methods like toUpperCase, toLowerCase, trim, split, and more. These methods are used to perform various operations on strings, such as changing their case, trimming whitespace, or splitting them into substrings.

Syntax of toUpperCase():

				
					toUpperCase()

Syntax:
val upperCaseString = originalString.toUpperCase()

				
			

Syntax of toLowerCase():

				
					val lowerCaseString = originalString.toLowerCase()

				
			

Syntax of trim():

				
					val trimmedString = originalString.trim()

				
			

Syntax of split():

				
					val splitString = originalString.split(" ")

				
			

Syntax of substring():

				
					val substring = originalString.substring(startIndex, endIndex)

				
			

Syntax of replace():

				
					val replacedString = originalString.replace("oldValue", "newValue")

				
			

Syntax of startsWithm k():

				
					val startsWithPrefix = originalString.startsWith("prefix")

				
			

Syntax of toLowerCase():

				
					val endsWithSuffix = originalString.endsWith("suffix")

				
			

Example

				
					fun main() {
    // Define a string
    val originalString = "   Kotlin String Manipulation   "

    // Convert the string to uppercase
    val upperCaseString = originalString.toUpperCase()

    // Convert the string to lowercase
    val lowerCaseString = originalString.toLowerCase()

    // Trim leading and trailing whitespace
    val trimmedString = originalString.trim()

    // Split the string into substrings
    val splitString = trimmedString.split(" ")

    // Print the results
    println("Original String: '$originalString'")
    println("Uppercase: '$upperCaseString'")
    println("Lowercase: '$lowerCaseString'")
    println("Trimmed: '$trimmedString'")
    println("Split: ${splitString.joinToString(", ")}")
}

				
			

Output:

				
					fun main() {
    // Define a string
    val originalString = "   Kotlin String Manipulation   "

    // Convert the string to uppercase
    val upperCaseString = originalString.toUpperCase()

    // Convert the string to lowercase
    val lowerCaseString = originalString.toLowerCase()

    // Trim leading and trailing whitespace
    val trimmedString = originalString.trim()

    // Split the string into substrings
    val splitString = trimmedString.split(" ")

    // Print the results
    println("Original String: '$originalString'")
    println("Uppercase: '$upperCaseString'")
    println("Lowercase: '$lowerCaseString'")
    println("Trimmed: '$trimmedString'")
    println("Split: ${splitString.joinToString(", ")}")
}