In java how to get substring from a string till a character c?

前端 未结 9 680
广开言路
广开言路 2020-12-04 16:26

I have a string (which is basically a file name following a naming convention) abc.def.ghi

I would like to extract the substring before the first

9条回答
  •  天涯浪人
    2020-12-04 16:32

    Here is code which returns a substring from a String until any of a given list of characters:

    /**
     * Return a substring of the given original string until the first appearance
     * of any of the given characters.
     * 

    * e.g. Original "ab&cd-ef&gh" * 1. Separators {'&', '-'} * Result: "ab" * 2. Separators {'~', '-'} * Result: "ab&cd" * 3. Separators {'~', '='} * Result: "ab&cd-ef&gh" * * @param original the original string * @param characters the separators until the substring to be considered * @return the substring or the original string of no separator exists */ public static String substringFirstOf(String original, List characters) { return characters.stream() .map(original::indexOf) .filter(min -> min > 0) .reduce(Integer::min) .map(position -> original.substring(0, position)) .orElse(original); }

提交回复
热议问题