简体   繁体   中英

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

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"

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

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 eg 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 .

下面的表达式描述了第二个子字符串是分隔符 x

yourText.split('x')[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM