Delete everything after part of a string

后端 未结 10 2063
时光取名叫无心
时光取名叫无心 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:00

    The apache commons StringUtils provide a substringBefore method

    StringUtils.substringBefore("Stack Overflow - A place to ask stuff", " - ")

    0 讨论(0)
  • 2020-12-03 10:02

    For example, you could do:

    String result = input.split("-")[0];
    

    or

    String result = input.substring(0, input.indexOf("-"));
    

    (and add relevant error handling)

    0 讨论(0)
  • 2020-12-03 10:03

    This will do what you need:

    newValue = oldValue.substring(0, oldValue.indexOf("-");
    
    0 讨论(0)
  • 2020-12-03 10:04

    You can use this

    String substr = mysourcestring.substring(0,mysourcestring.indexOf("-"));
    
    0 讨论(0)
  • 2020-12-03 10:05

    you can my utils method this action..

    public static String makeTwoPart(String data, String cutAfterThisWord){
        String result = "";
    
        String val1 = data.substring(0, data.indexOf(cutAfterThisWord));
    
        String va12 = data.substring(val1.length(), data.length());
    
        String secondWord = va12.replace(cutAfterThisWord, "");
    
        Log.d("VAL_2", secondWord);
    
        String firstWord = data.replace(secondWord, "");
    
        Log.d("VAL_1", firstWord);
    
        result = firstWord + "\n" + secondWord;
    
    
        return result;
    }`
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题