【问题标题】:How to split/substring as given string in below format using java如何使用 java 以下面的格式拆分/子字符串为给定的字符串
【发布时间】:2022-12-20 06:11:35
【问题描述】:

我想使用 java 或 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.

【问题讨论】:

    标签: java spring java-8


    【解决方案1】:

    您可以使用 String.split() 方法和 "\." 作为您的输入。这会将整个字符串拆分为一个字符串数组。然后你可以在第一个空间分裂。

    例子:

    假设您要创建的对象名为 A

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

    然后你可以这样做:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 1970-01-01
      • 2012-07-22
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多