简体   繁体   中英

How to split/substring as given string in below format using java

i want to substring or split into List of Objects of number & description using java or java 8/9

"9 music recordings; Music files to download. 38 Providing access to music databases and to MP3 websites. 41 Organization of live musical events; Music publishing services; conducting music events; composing music for others; live entertainment production; live performances by musical bands; musical performances; music production; composing music; Operating a music recording studio."

The desired result is

List(0) object: number = 9 ,description = music recordings; Music files to download. 
List(1) object: number = 38 ,description = Providing access to music databases and to MP3 websites.
List(2) object: number = 41 ,description = Organization of live musical events; Music publishing services; conducting music events; composing music for others; live entertainment production; live performances by musical bands; musical performances; music production; composing music; Operating a music recording studio.

You can use the String.split() method with "\\." as your input. This will split the whole string into an array of strings. Then you can split on the first space.

Example:

Assuming the object you're trying to create is called A

class A {
    public A(int num, String description);
}

then you can do:

String str = ...
String[] strings = str.split("\."); // the \\ is so the regex engine doesn't think it's a wildcard character
for (String elem : strings) {
    elements = elem.split(" ", 2); // the 2 is so that it only splits into two strings on the first space
    int number = Integer.valueOf(elements[0]);
    A object = A(number, elements[1]); // do what you want with the object, add it to an array, whatever
}

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