Kotlin: How do I get characters after "@" in a string?

While there's nothing wrong with the accepted answer the Kotlin standard library is worth exploring as it contains nice little methods like substringAfterLastwhich would shorten the example to this

val string = "[email protected]"

val domain: String? = string.substringAfterLast("@")

Note: Ivan Wooll's answer brings up the point of using substringAfterLast, which is a very useful utility, though it is important to keep in mind that it cannot return null and instead defaults to a provided default value (this is the original string, if nothing is specified).

I personally prefer dealing with null in cases where invalid input is a reasonable concern, rather than e.g. an empty string, because it's a much clearer indication that the delimiter was not found, and this special case can be easily handled by chaining ?:, ?., let, etc.

Here's an example of possibly-unwanted behavior:

string           | string.substringAfterLast("@")
-------------------------------------------------
"domain.com"     | "domain.com" !
"@domain.com"    | "domain.com"
"[email protected]" | "domain.com"

Just for the sake of completeness:

val string = "[email protected]"

val index = string.indexOf('@')

val domain: String? = if (index == -1) null else string.substring(index + 1)

This assigns the part after @ to domain if it exists, otherwise null.


For learning, IntelliJ's Java -> Kotlin converter may be of use.

By default, this shortcut is usually mapped to Ctrl+Alt+Shift+K.

You could even make this an extension property:

val String.domain: String?
    get() {
        val index = string.indexOf('@')
        return if (index == -1) null else string.substring(index + 1)
    }

and then you would be able to do

println("[email protected]".domain)

You could shorten this code to one line with let:

string.indexOf('@').let { if (it == -1) null else string.substring(it + 1) }

Here's a similar question in Java.