21

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"

Daniel Dramond
  • 1,538
  • 2
  • 15
  • 26

3 Answers3

49

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 = "hello@world.com"

val domain: String? = string.substringAfterLast("@")
Ivan Wooll
  • 4,145
  • 3
  • 23
  • 34
  • 2
    I like this one better. In this case, you don't even need the index value. – Fabricio Lemos Nov 29 '17 at 22:08
  • 5
    Nice find, though [`substringAfterLast`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/substring-after-last.html) doesn't return a nullable string - the default value is the string itself. Whether this is desired depends on the use. – Salem Nov 30 '17 at 07:01
13

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.

Salem
  • 13,516
  • 4
  • 51
  • 70
0

The following expression describes the second substring be the delimiter character x

yourText.split('x')[1]
Braian Coronel
  • 22,105
  • 4
  • 57
  • 62