简体   繁体   中英

Is there a way to split a string after a certain number of characters in Java?

Say I have a string "yyyymmddword", Is there a method I could use to have an int year, month, day, and String word based on that string. So if I have a string "20070405word", I need to convert it to:

String name = "yyyymmddword";
int year = 2007;
int day = 04;
int month = 05;
String word = "word";

How can I write a method that can allow me to split that string without manually assigning these variables?

To base purely off the index of the character String.substring() is perfectly suitable.

public static void main(String args[]) {
    String s = "yyyymmddword";

    System.out.println(s.substring(0,4));
    System.out.println(s.substring(4,6));
    System.out.println(s.substring(6,8));
    System.out.println(s.substring(8));        
}

Output:

yyyy
mm
dd
word

Try this:

String name = "yyyymmddword";
int year = Integer.parseInt(name.substring(0, 4));
int day = Integer.parseInt(name.substring(4, 6));
int month = Integer.parseInt(name.substring(6, 8));
String year = Integer.parseInt(name.substring(8));

Yes there is. All you need to do is create more Strings, then use the substring() method. Follow my example below.

    String word = "TestString";
    String new1 = word.substring(0,4); 
    /*substring() goes from the first specified index, up to, but not including
    * the second.
    */
    String new2 = word.substring(4,word.length() + 1);
    System.out.println(word + "\n" + new1 + "\n" + new2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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