Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中重写共享类似模式的字符串?_Java_String - Fatal编程技术网

如何在Java中重写共享类似模式的字符串?

如何在Java中重写共享类似模式的字符串?,java,string,Java,String,我有一个日期列表,其格式如下: 20130103 20130104 20130105 20130106 20130107 我想把它们改写成这样: 01/02/2013 01/03/2013 01/04/2013 01/05/2013 01/06/2013 01/07/2013 在Java中有什么方法可以做到这一点吗 日期存储在一个文本文件中,因此我使用扫描仪逐个读取日期并将其存储到字符串数组中,但我无法确定下一步要做什么。是的,您可以使用正则表达式对前四位数字、后两位数字和最后两

我有一个日期列表,其格式如下:

20130103   
20130104
20130105  
20130106
20130107
我想把它们改写成这样:

01/02/2013
01/03/2013
01/04/2013
01/05/2013
01/06/2013
01/07/2013 
在Java中有什么方法可以做到这一点吗

日期存储在一个文本文件中,因此我使用扫描仪逐个读取日期并将其存储到字符串数组中,但我无法确定下一步要做什么。

是的,您可以使用正则表达式对前四位数字、后两位数字和最后两位数字进行分组。并将这些组改写为您想要的格式。大概

String[] dates = { "20130102", "20130103", "20130104", //
        "20130105", "20130106", "20130107" };
for (String date : dates) {
    System.out.println(date.replaceAll("(\\d{4})(\\d{2})(\\d{2})", "$2/$3/$1"));
}
产出(按要求)

//int intDateSlash=Integer.parseInt(4char)

这是一个数字,但我希望你能理解

如果需要,使用
java.time
api将具有将日期验证为有效日期的优势。以下是一个例子:

public static final DateTimeFormatter PARSER = DateTimeFormatter.ofPattern("yyyyMMdd");
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("MM/dd/yyyy");

public static String convert(String date){
    return LocalDate.parse(date, PARSER).format(FORMATTER);
}

读了4个字,就得到了这一年。多读两个字,就得到了这个月。再看两个字,就有一天了。重新排序并加入分隔符。请解释您答案的更多细节
public String convertDate(String origDate)
{
    if (origDate.length == 8)
    {
        String year = origDate.substring(0, 4);
        String month = origDate.substring(4, 6);
        String day = origDate.substring(6, 8);
        return month + "/" + day + "/" + year;
    }
    else
    {
        return "Invalid Date Format";
    }
}
String str = "20160428";
//int dateInt = Integer.parseInt(str); //this is to read the string into int
String 4char = str.substring(0,4);   //read int based of array type (starting position which is 0 and read up to position 3)
String 2char = str.substring(4,6)
String last2char = str.substring(6,7)
public static final DateTimeFormatter PARSER = DateTimeFormatter.ofPattern("yyyyMMdd");
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("MM/dd/yyyy");

public static String convert(String date){
    return LocalDate.parse(date, PARSER).format(FORMATTER);
}