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

前端 未结 9 615
广开言路
广开言路 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:44

    If your project already uses commons-lang, StringUtils provide a nice method for this purpose:

    String filename = "abc.def.ghi";
    
    String start = StringUtils.substringBefore(filename, "."); // returns "abc"
    

    see javadoc [2.6] [3.1]

    0 讨论(0)
  • 2020-12-04 16:46

    You can just split the string..

    public String[] split(String regex)
    

    Note that java.lang.String.split uses delimiter's regular expression value. Basically like this...

    String filename = "abc.def.ghi";     // full file name
    String[] parts = filename.split("\\."); // String array, each element is text between dots
    
    String beforeFirstDot = parts[0];    // Text before the first dot
    

    Of course, this is split into multiple lines for clairity. It could be written as

    String beforeFirstDot = filename.split("\\.")[0];
    
    0 讨论(0)
  • 2020-12-04 16:50

    or you may try something like

    "abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);

    0 讨论(0)
提交回复
热议问题