【问题标题】:How to extract content from a string (Java)如何从字符串中提取内容(Java)
【发布时间】:2021-09-24 23:57:02
【问题描述】:

我想知道如何提取字符串的某个部分。例如,我正在做一些事情,要求用户以 MM/DD/YYYY 或 M/D/YYYY 格式输入日期,而我想要做的是提取月份。我看到了 substring 方法,但该月可能有超过 1 个数字。另外,我尝试过 indexOf,但它需要一个 int 值,而不是符号。

String startDateInput = "12/09/2015";

String getMonthStart = startDateInput.substring(1, indexOf("/"));

【问题讨论】:

  • 你非常接近,只是使用索引有点不同String getMonthStart = startDateInput.substring(0, startDateInput.indexOf('/'));

标签: java string indexing methods substring


【解决方案1】:

试试这个,

 String startDateInput="12/09/2015";
 String month=startDateInput.substring(0,startDateInput.indexOf('/'));

【讨论】:

    【解决方案2】:

    您不必拆分 String,您可以将其解析为 LocalDate,然后根据您想要的结果(当月的名称或编号)调用 getMonth()getMonthValue()

    如果您使用"M/d/uuuu""M/d/yyyy" 模式创建java.time.DateTimeFormatter,它将解析Strings,如"12/09/2015""2/9/2015"

    public static void main(String[] args) throws Exception {
        // provide some example date as String
        String input = "12/09/2015";
        // define a formatter that is capable of parsing such a String
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uuuu");
        // parse it to a suitable object using the formatter
        LocalDate localDate = LocalDate.parse(input, dtf);
        // extract the Month from it
        Month month = localDate.getMonth();
        // or directly get the number of that month in a year
        int monthVal = localDate.getMonthValue();
        // use the month and a desired locale to determine the month name
        String monthNameEn = month.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
        // print some super meaningful example output
        System.out.println(String.format("%s is month no. %d in a year",
                                         monthNameEn, monthVal));
    }
    

    这个输出

    December is month no. 12 in a year
    

    这并不像拆分输入和提取月份数字那么短,但它提供了更多的可能性,比如获取不同语言的月份或星期几的名称等。

    【讨论】:

      【解决方案3】:

      你可以在这里使用String#split

      String startDateInput = "12/09/2015";
      String getMonthStart = startDateInput.split("/")[0];
      System.out.println(getMonthStart);  // 12
      

      或者,我们可以使用正则表达式替换方法:

      String startDateInput = "12/09/2015";
      String getMonthStart = startDateInput.replaceAll("/.*$", "");
      System.out.println(getMonthStart);  // 12
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-07
        • 2019-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多