String Methods

Reading Time: 2 minutes

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.

.SUBSTRING(STARTINDEX: INT)

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.

 // spire_coding

.SUBSTRING(STARTINDEX: INT, ENDINDEX: INT)

You can also specify the start and endIndex of the source string to extract the substring.

 // spire C
Note that the whitespace is also a valid character between the MY_NAME string.

.SUBSTRINGAFTER(
    DELIMITER: STRING,
    MISSINGDELIMITERVALUE: STRING = THIS)

Sometimes, you need to get a substring using a defined delimiter parameter. The result you get is the substring after the first appearance of delimiter.

 // spire C

If you change the delimiter value to something which does not exist inside the source string then the missingDelimiterValue will be returned which is “Delimiter not found”.

.SUBSTRINGBEFORE(
    DELIMITER: STRING,
    MISSINGDELIMITERVALUE: STRING = THIS)

With this method you can get the substring before the first appearance of delimiter.

 // spire C

Here again, if you change the delimiter value to something which does not exist inside the source string then the missingDelimiterValue will be returned which is “Delimiter not found”.

.SUBSTRINGAFTERLAST(
    DELIMITER: STRING,
    MISSINGDELIMITERVALUE: STRING = THIS)

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.

 // spire C

If you had a test which contains the two same delimeter and you only want to get the substring after the last delimiter then this method is perfect for our logic.

.SUBSTRINGBEFORELAST(
    RANGE: STRING,
    MISSINGDELIMITERVALUE: STRING = THIS)

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.

 // spire C

.SUBSTRING(RANGE: INTRANGE)

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.

 // spire C

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications