简体   繁体   English

查找两个“ /”之间的子字符串

[英]Find the substring between two “/”

For this program the user is told to input a data in the form of "mm/dd/yyyy" and I'm trying to use the indexOf() method with the parameter of "/" to break the date string into three substrings. 对于此程序,系统要求用户以“ mm / dd / yyyy”的形式输入数据,而我试图使用带有参数“ /”的indexOf()方法将日期字符串分成三个子字符串。

I tried doing this: 我尝试这样做:

String monthString = dateString.substring(0,dateString.indexOf("/"));
    String dayString = 
    dateString.substring(dateString.indexOf("/"),DateString.indexOf("/")+1)

Thank you. 谢谢。 Edit. 编辑。 Thank you all for your responses, but my teacher said that i cannot use the split fucntion. 谢谢大家的答复,但是我的老师说我不能使用分割功能。 He said I can solve this using just indexOf("/") and substring(). 他说我可以只使用indexOf(“ /”)和substring()解决此问题。 I'll need two calls to indexOf("/") and four calls to substring(). 我需要两次调用indexOf(“ /”)和四个调用substring()。

String[] element = dateString.split("/");
String strDay = element[0];
String strMonth = element[1];
String strYear = element[2];

This is what you're looking for. 这就是您要寻找的。

Instead of split() method you can use Java Date API 可以使用Java Date API代替split()方法

  String dateString = "10/30/2018";
    try {
        DateFormat dateFromatter = new SimpleDateFormat("MM/dd/yyyy");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateFromatter.parse(dateString));
        System.out.println("Date:" + calendar.get(Calendar.DATE));
        System.out.println("Month:" + calendar.get(Calendar.MONTH));
        System.out.println("Year:" + calendar.get(Calendar.YEAR));
    } catch (Exception e) {
        e.printStackTrace();
    }

Output 产量

Date:30
Month:9
Year:2018

For month field Calendar.MONTH starts from 0 which mean Jan=0,Feb=1 Refer Java Doc 对于月份字段Calendar.MONTH从0开始,这意味着Jan = 0,Feb = 1引用Java Doc

dateString.split("[/]"); gives you the array of string. 给您字符串数组。 split() function take input in regex thats why "[]" are added. split()函数在regex接受输入,这就是为什么要添加"[]"原因。

if the dateString is "dd/mm/yy" then dateString.split("[/]") return the String array consists of {"dd","mm","yy"} . 如果dateString为“ dd / mm / yy”,则dateString.split("[/]")返回由{"dd","mm","yy"}组成的String数组。

If you are using Java 8 or above and actually you are handling date and time , then I think you should have a try at LocalDate.parse and as to your problem then you can achieve it easily as: 如果您使用的是Java 8或更高版本,并且实际上正在处理date和time ,那么我认为您应该尝试使用LocalDate.parse并针对您的问题进行尝试,然后可以轻松实现该目标:

LocalDate theDate = LocalDate.parse("08/22/2018", DateTimeFormatter.ofPattern("MM/d/yyyy"));
System.out.println("year: " + theDate.getYear() + " month: " + theDate.getMonthValue() + " day: " + theDate.getDayOfMonth());

the output will be: 输出将是:

year: 2018 month: 8 day: 22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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