Delete everything after part of a string

后端 未结 10 2148
时光取名叫无心
时光取名叫无心 2020-12-03 09:25

I have a string that is built out of three parts. The word I want the string to be (changes), a seperating part (doesn\'t change) and the last part which changes. I want to

10条回答
  •  时光取名叫无心
    2020-12-03 10:06

    Kotlin Solution

    Use the built-in Kotlin substringBefore function (Documentation):

    var string = "So much text - no - more"
    string = string.substringBefore(" - ") // "So much text"
    

    It also has an optional second param, which is the return value if the delimiter is not found. The default value is the original string

    string.substringBefore(" - ", "fail")  // "So much text"
    string.substringBefore(" -- ", "fail") // "fail"
    string.substringBefore(" -- ")         // "So much text - no - more"
    

提交回复
热议问题