I have a string that is an email. I want to be able to get the domain part of the email no matter what the string/email is. Essentially I'm wanting to get hold of the characters after the @ part of the string. For example, for testing@kotlin.com, I'm after the kotlin.com part.
val emailString = "hello@world.com"
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"
"foo@domain.com" | "domain.com"
Just for the sake of completeness:
val string = "hello@world.com"
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("hello@world.com".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.