Remove part of string in Java

后端 未结 12 1732
遥遥无期
遥遥无期 2020-11-28 04:22

I want to remove a part of string from one character, that is:

Source string:

manchester united (with nice players)

Target string:

12条回答
  •  醉梦人生
    2020-11-28 04:49

    Kotlin Solution

    If you are removing a specific string from the end, use removeSuffix (Documentation)

    var text = "one(two"
    text = text.removeSuffix("(two") // "one"
    

    If the suffix does not exist in the string, it just returns the original

    var text = "one(three"
    text = text.removeSuffix("(two") // "one(three"
    

    If you want to remove after a character, use

    // Each results in "one"
    
    text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
    // or
    text = text.removeRange(text.indexOf("("), text.length)
    // or
    text = text.replaceRange(text.indexOf("("), text.length, "")
    

    You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar

    The Full List is here: (Documentation)

提交回复
热议问题