简体   繁体   English

分割Java字串

[英]Splitting a Java String

I have a YYYYMM date in String format. 我有一个String格式的YYYYMM日期。 I want to split it into YYYY and MM and replace the existing YYYY with a new year and concatenate it back in Java. 我想将其分为YYYYMM并用新的年份替换现有的YYYY ,然后将其重新连接到Java中。

For example, I have 201201 . 例如,我有201201 I want to split it into 2012 and 01 and change 2012 to 2000 and finally get 200001 . 我想将其拆分为201201 ,并将2012更改为2000 ,最后得到200001 How do I do it? 我该怎么做?

I googled it but everyone seemed to have a - or a * in between. 我用谷歌搜索,但每个人之间似乎都有-*

Or if anyone knows a better way to do it (maybe change it into a Date and modify the year), I am all ears. 或者,如果有人知道一种更好的方法(可能将其更改为“ Date并修改年份),那我真是无所适从。

Any help would be appreciated! 任何帮助,将不胜感激!

Thanks 谢谢

One uber-simple approach is just to use string manipulation: 一种非常简单的方法就是使用字符串操作:

String orig = "201201";
String changed = "2000" + orig.substring(4);

EDIT: A looping example, as per the comment: 编辑:一个循环的示例,根据注释:

// Loop over the inputs
for (String date : getDatesFromFile() {
    // Loop over 10 years:
    for (int year = 2000; year <= 2010; ++year) {
        String newDate = String.valueOf(year) + date.substring(4);

        // write newDate to an output file
    }
}

Take a look to this code to see if it can help you. 看一下这段代码,看看它是否可以帮助您。

 String myDate = "201201";
  String myDate1 = myDate.substring(0, 4);
  String myDate2 = myDate.substring(4);
  myDate1 = "2000"; //Change the logic accordingly with your spec
  System.out.println(myDate1 + myDate2);

try This : 尝试这个 :

  String Str = new String("201201");
  System.out.print("Replace Year :" );
  System.out.println(Str.replace('2012', '2000'));

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

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