Delete everything after part of a string

2020-02-05 01: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 delete the seperating part and the ending part. The seperating part is " - " so what I'm wondering is if theres a way to delete everything after a certaint part of the string.

An example of this scenario would be if I wanted to turn this: "Stack Overflow - A place to ask stuff" into this: "Stack Overflow". Any help is appreciated!

10条回答
该账号已被封号
2楼-- · 2020-02-05 01:59

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;
查看更多
爷、活的狠高调
3楼-- · 2020-02-05 02:02

You can use this

String substr = mysourcestring.substring(0,mysourcestring.indexOf("-"));
查看更多
爷、活的狠高调
4楼-- · 2020-02-05 02:08
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);
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-02-05 02:10

This will do what you need:

newValue = oldValue.substring(0, oldValue.indexOf("-");
查看更多
登录 后发表回答