22

A-Z Useful SubString Methods In Kotlin String Class

 4 years ago
source link: https://www.tuicool.com/articles/QbEZBbr
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

One of the common operation when working with strings is to extract a substring of another string. There are several subString methods added to Kotlin String class as extension functions and we’re going to see them one-by-one.

So, in this quick article, we’ll talk about how to use different substring methods in Kotlin.

.subString(startIndex: Int) Method

The above subString method returns a new string that starts from the specified startIndex and ends at right before the length of the calling string.

private const val MY_NAME = "Ahsen Saeed"

fun main() {
    val result = MY_NAME.substring(startIndex = 2)
    println(result)
}

Now, if you try to run the above code you’ll notice that the startIndex start from zero and it is inclusive.

.subString(startIndex: Int, endIndex: Int) Method

You can also specify the start and endIndex of the source string to extract the substring. The complete syntax is as follows:

private const val MY_NAME = "Ahsen Saeed"

//sampleStart
fun main() {
    val result = MY_NAME.substring(startIndex = 2, endIndex = 8)
    println(result)
}
//sampleEnd

In the above example, the startIndex is where you want to get a substring from and endIndex specifies the end position in the source string.

Note:Space is also a valid character between the MY_NAME string.

.substringAfter(delimiter: String, missingDelimiterValue: String = this) Method

At some point, you may need to get a substring using a defined delimiter parameter. The result you get is the substring after the first appearance of delimiter . If the source string does not contain the delimiter , then the missingDelimeterValue will be returned which defaults to the source string.

Let’s take a look at the complete syntax of substringAfter method:

private const val FILE_PATH = "/storage/emulated/0/DCIM/Camera/bed1285d9cefce2c0351462547e3259f.mp4"

fun main() {
    val extension = FILE_PATH.substringAfter(delimiter = ".", missingDelimiterValue = "Extension Not found")
    println("File extension -> $extension")
}

The above program will successfully give you the mp4 extension name of the file. But if we change the delimiter value to something which does not exist inside the source string then the missingDelimiterValue will be returned which is Extension Not Found .

You can also pass the delimiter as a Char .

.substringBefore(delimiter: String, missingDelimiterValue : String = this) Method

Above, in the last method, I mention how we can get the substring after the first appearance of delimiter. Well, with this method we can get the substring before the first appearance of delimiter .

Here’s a concrete example of using the substringBefore method.

private const val MY_EMAIL = "<a href="/cdn-cgi/l/email-protection" data-cfemail="6f0e071c0e011c0e0a0a0b5f59582f08020e0603410c0002">[email protected]</a>"

fun main() {
   val username = MY_EMAIL.substringBefore(delimiter = "@", missingDelimiterValue = "Usernmae Not Found")
   println("Username -> $username")
}

You can see, the above program returns the substring before the appearance of @ character.

Same as the above method you can pass the delimiter parameter as a Char .

.substringAfterLast(delimiter : String, missingDelimiterValue : String= this) Method

I know, the name of this method had a similarity to substringAfter but it works a little different than the other. So, this substring method starts finding the delimiter value from the right side of the source string and returns a substring after the last occurrence of delimiter .

Now if I had a file path which contains the two same delimeter and I only want to get the substring after the last delimiter then this method is perfect for our logic.

Let’s see a working example:

private const val FILE_PATH = "/storage/emulated/0/DCIM/Camera/.bed1285d9cefce2c0351462547e3259f.mp4"

fun main() {
    val fileExtension = FILE_PATH.substringAfterLast(delimiter = ".", missingDelimiterValue = "Extension Not found")
    println("File extension -> $fileExtension")
}

Awesome! the substringAfterLast method successfully gives the file extension although the FILE_PATH contains two delimiter value well, that’s because the method starts searching from right-side of source string.

.substringBeforeLast(delimiter: String, missingDelimiterValue : String= this) Method

The only difference between this substring method and previous: this method returns the substring before the last occurrence of the delimiter. The method also starts searching from right-side and when finds the first delimiter it returns the left-sided substring which not even used for searching.

private const val MY_EMAIL = "<a href="/cdn-cgi/l/email-protection" data-cfemail="6c0d041f0d022c1f0d0909085c5a5b">[email protected]</a>@gmail.com"

fun main() {
    val username = MY_EMAIL.substringBeforeLast(delimiter = '@', missingDelimiterValue = "Username not found")
    println("Username -> $username")
}

I know! that’s not a valid email address but this is only for example. The moment substringBeforeLast method finds the first @ delimiter from the right side even though the MY_EMAIL has two @ delimiters. It’ll return the remaining left side substring without going further.

.substring(range: IntRange) Method

Now if you want a substring specified by the given Range indices then this method is what you’re looking for. Internally this method calls the substring(startIndex , endIndex) method. Here’s the implementation of substring(range: IntRange).

public fun String.substring(range: IntRange): String = substring(range.start, range.endInclusive + 1)

The following shows the working example:

private const val MY_NAME = "Ahsen Saeed"

fun main() {
    val firstName = MY_NAME.substring(range = 0..4)
    println(firstName)
}

There you have it! It’s really easy to extract a substring in Kotlin with the above extension functions. I hope, I educate you more in Kotlin.

Thank you for being here and keep reading…


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK