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 [email protected], I'm after the kotlin.com part.
val emailString = "[email protected]"
Method 1: Using substring : To get the last index, method lastIndexOf can be used. The last index of / is 7 and the substring starts from index 8 i.e. from the first w. If the character is not in that string, lastIndexOf will return -1 and substring will return the complete string.
To iterate over each character in the String in Kotlin, use String. iterator() method which returns an iterator for characters in this string, and then use For Loop with this iterator. In the following example, we take a string in str1 , and iterate over each character in this string using String.
While there's nothing wrong with the accepted answer the Kotlin standard library is worth exploring as it contains nice little methods like substringAfterLast
which 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With