如何拆分包含String和Int的文本并存储到ArrayList中?

时间:2015-12-17 16:04:51

标签: java string arraylist split store

所以基本上我有一个使用BufferedReader读取txt文件的java程序。

文本文件包含有关电影的所有信息。第一列是代码,第二列是标题,第三列是评级 e.g

1 Titanic 44  
34 Avengers 60  
2 The Lord of the Rings 100

所以1是代码,泰坦尼克号是标题,44是评级等。

我的问题是我制作了一个类Movie(int code,String title,int rating) 我想在那里存储所有信息,但我无法弄清楚如何拆分文本。 split(" ")似乎不会处理标题嵌入空格的情况(例如指环王)。

我真正需要的是能够根据空格剥离第一个和最后一个字段作为分隔符,并将所有其他内部空间视为标题的一部分,而不是分隔符。

5 个答案:

答案 0 :(得分:6)

你是对的,你已经尝试的split是不合适的。根据您显示的模式,分隔符似乎是每行中的第一个和最后一个空格,它们之间的所有内容都是标题。我建议找到这些空格的索引并使用substring()

例如:

String text = "2 The Lord of the Rings 100";
int firstSpace = text.indexOf(' ');
int lastSpace = text.lastIndexOf(' ');

String codeText = text.substring(0, firstSpace);
String title = text.substring(firstSpace, lastSpace);
String ratingText = text.substring(lastSpace);

答案 1 :(得分:2)

你可以使用拆分("") 使用

String[] foo = split(" ")

foo中的第一个元素是第一个整数。将其转换为整数类型。然后逐步执行其余元素并将它们附加到一个字符串中,除了foo中的最后一个元素,这将是您的最后一个整数,您可以将其转换为整数类型。

答案 2 :(得分:1)

您可以尝试使用我不能使用split("")因为某些标题(例如指环王)在标题之间有空格。

String str = "2 The Lord of the Rings 100";
String[] arr = str.split("\\s+");
List<String> list = Arrays.asList(arr);

获取arr

的数据
String code  = arr[0];
String rate = arr[arr.length-1];
String title = "";
for (int i = 1; i < arr.length-1; i++) {
    title += arr[i]+" ";
}

运行代码

System.out.println("code = " + code);
System.out.println("rate = " + rate);
System.out.println("title = " + title);

结果是:

code = 2
rate = 100
title = The Lord of the Rings

这可以帮助你......

答案 3 :(得分:1)

使用模式(\d*)\s(.*)\s(\d*)

查看Regexp和Matcher类

编辑:示例

@Test
public void testRegExp(){
    String text = "2 The Lord of the Rings 100";
    String patternString = "(\\d*)\\s(.*)\\s(\\d*)";
    Pattern pattern = Pattern.compile(patternString);

    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        System.out.println("CODE : " + matcher.group(1));
        System.out.println("TITLE : " + matcher.group(2));
        System.out.println("RATE : " + matcher.group(3));
    }
}

答案 4 :(得分:-2)

$(function() {
    $(window).on('resize', function() {
        $('#fitin').css('font-size', '1em');
        var count = 0;
        while( count< 30 && $('#fitin').height() > $('#fitin div').height() ) { 
            $('#fitin *').each(function( index ) {
                $(this).css('font-size',(parseInt($(this).css('font-size')) + 1) + "px");
            });
            count++;
        } 
        count = 0;
        while( count< 30 && $('#fitin div').height() > $('#fitin').height()-20 ) {
            $('#fitin *').each(function( index ) {
                $(this).css('font-size',(parseInt($(this).css('font-size')) - 1) + "px");
            })
            count++;
        }
    });
    $(window).trigger('resize');  
});