【问题标题】:Splitting tokens into tokens using delimiters in Java在 Java 中使用分隔符将标记拆分为标记
【发布时间】:2016-10-13 00:10:43
【问题描述】:

我有以下 txt 文件,我需要用令牌拆分并保存到一个对象:

1,哈利波特,4,3,11,14,20

2,矩阵,3,1,8,12

3,蝙蝠侠,3,39,9,42

结构是:id、name、length、movieIds

其中长度是指有多少个movieId。

不确定如何分别拆分movieIds 或为对象设置多个值,因为它们会相互覆盖。

Scanner inputFile = new Scanner(playlistLibrary);

        String str;
        String[] tokens;        

        for (int i = 1; i < playlist.length; i ++) {

            playlist[i] = new Playlist_17967352();

            if (inputFile.hasNext()) {

                str = inputFile.nextLine();
                tokens = str.split(","); 


                for (int a = 0; a < tokens.length; a ++) {

                    playlist[i].setId(tokens[0]);
                    playlist[i].setName(tokens[1]);
                    playlist[i].setLength(tokens[2]);

                    if (tokens.length > 3) {

                    int length = Integer.parseInt(playlist[i].getLength()); 

                            String movieIds;    

                        for (int b = 0, c = 3 ; b < length; b++, c++) {

                            movieIds = tokens[c];                                   
                            playlist[i].setMovies(movieIds);                                
                        }

                    }

                } // end for tokens.length  

                System.out.println(playlist[i].getMovies());

代码输出:

20

12

42

我需要的是:

3,11,14,20

1,8,12

39,9,42

【问题讨论】:

  • 是否可以更新文件格式? 1,哈利波特,4,"3,11,14,20" 2,矩阵,3,"1,8,12" 3,蝙蝠侠,3,"39,9,42"
  • 看起来像 CSV (Comma-Separated Values) 数据,所以使用 CSV 解析器,例如Apache Commons CSV.
  • @Andreas 是的,但他的 CSV 格式不会转义movieIds,因此除非他添加引号,否则它将无法正常工作
  • setMovies() 的签名是什么?
  • @42shadow42 在 Java 结构中将movieIds 存储为逗号分隔的字符串不是正确的答案(在我看来)。它应该是List&lt;Integer&gt;int[]。因此,这些值是 CSV 文本中真正独立的值。

标签: java arrays class token delimiter


【解决方案1】:

你可以只做一次拆分。您知道第一个电影 id 位于 tokens[3],因此您只需要在循环中使用一个计数器,然后在索引 tokens 时添加 3。

【讨论】:

  • 不确定我是否遵循,您的意思是将行分成 2 行吗?
猜你喜欢
  • 2010-10-14
  • 2010-12-26
  • 1970-01-01
  • 2023-04-10
  • 2015-12-20
  • 2011-02-27
  • 2013-09-15
  • 1970-01-01
相关资源
最近更新 更多