Delete everything after part of a string

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

    Perhaps thats what you are looking for:

    String str="Stack Overflow - A place to ask stuff";
    
    String newStr = str.substring(0, str.indexOf("-"));
    
    0 讨论(0)
  • 2020-12-03 10:11

    Clean way to safely remove until a string, and keep the searched part if token may or may not exist.

    String input = "Stack Overflow - A place to ask stuff";
    String token = " - ";
    String result = input.contains(token)
      ? token + StringUtils.substringBefore(string, token)
      : input;
    // Returns "Stack Overflow - "
    

    Apache StringUtils functions are null-, empty-, and no match- safe

    0 讨论(0)
  • 2020-12-03 10:12
    String line = "deltaasm:/u01/app/oracle/product/11.2.0/dbhome_1:N        # line addred by agent";
    
        String rep = "deltaasm:";
        String after = "";
    
        String pre = ":N";
        String aft = "";
        String result = line.replaceAll(rep, after);
        String finalresult = result.replaceAll(pre, aft);
        System.out.println("Result***************" + finalresult);
    
        String str = "deltaasm:/u01/app/oracle/product/11.2.0/dbhome_1:N        # line addred by agent";
    
        String newStr = str.substring(0, str.indexOf("#"));
        System.out.println("======" + newStr);
    
    0 讨论(0)
  • 2020-12-03 10:16

    I created Sample program for all the approches and SubString seems to be fastest one.

    Using builder : 54
    Using Split : 252
    Using Substring  : 10
    

    Below is the sample program code

                for (int count = 0; count < 1000; count++) {
            // For JIT
        }
        long start = System.nanoTime();
        //Builder
        StringBuilder builder = new StringBuilder(
                "Stack Overflow - A place to ask stuff");
        builder.delete(builder.indexOf("-"), builder.length());
        System.out.println("Using builder : " + (System.nanoTime() - start)
                / 1000);
        start = System.nanoTime();
        //Split
        String string = "Stack Overflow - A place to ask stuff";
        string.split("-");
        System.out.println("Using Split : " + (System.nanoTime() - start)
                / 1000);
        //SubString
        start = System.nanoTime();
        String string1 = "Stack Overflow - A place to ask stuff";
        string1.substring(0, string1.indexOf("-"));
        System.out.println("Using Substring : " + (System.nanoTime() - start)
                / 1000);
        return null;
    
    0 讨论(0)
提交回复
热议问题