简体   繁体   中英

How to remove specific line from multi-line string

I have below java string as command output

String output = "NIC     Value\n"
                + "------  -----\n"
                + "vmn0  on   \n"
                + "vmn1  on   \n"
                + "vmn2  on   \n"
                + "vmn3  on   \n"
                + "vmn4  on";

I want to remove second line with dash from above string. How can I do it?

I tried it using contains method but it is generating blank line after removing second line.

 if(output!=null && output.contains("-"))
            output = output.replace("-","");

This is complete answer you are looking for:

String output = "NIC     Value\n"
            + "------  -----\n"
            + "vmn0  on   \n"
            + "vmn1  on   \n"
            + "vmn2  on   \n"
            + "vmn3  on   \n"
            + "vmn4  on";

    String str = Stream.of(output.split("\n"))
                       .filter(s -> !s.contains("--"))
                       .collect(Collectors.joining("\n"));

You can use this to remove that line and use the result,

String result = output.replace("------  -----\n", "");

It will replace that line with an empty String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM