【问题标题】:How to split strings into columns如何将字符串拆分为列
【发布时间】:2013-01-19 11:14:08
【问题描述】:

我在单列中有一个字符串列表。我想从这些字符串中创建三列,然后将输出打印到另一个文件。我该怎么做?

这是我迄今为止尝试过的:

ArrayList<String> list=new ArrayList<String>();
File file = new File("f://file.txt");

try {
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        System.out.println(line);
    }

    scanner.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

我的输入数据:

City
Gsk
Relocation
sripallu
here
jrajesh
gurgaon
unitech
StatisticsThreads
WizOty
LTDParsvnathK
Quotesby
newest
PMaashuktr

我的预期输出:

City      Gsk      Relocation
sripallu here      jrajesh
gurgaon  unitech   StatisticsThreads
WizOty   LTDParsvnathK  Quotesby
newest   PMaashuktr      Loans
.
.
.
.
.
.
.

【问题讨论】:

  • 您打算如何拆分列?分隔符是什么?
  • 分割分隔符还是输出分隔符?
  • My code what I tried 我在这里看不到任何拆分列的逻辑。这不是一个尝试!
  • @NarendraPathai OP 说拆分只需要一列
  • 你不能仅仅通过发布一些甚至不值得尝试的代码来逃避!

标签: java


【解决方案1】:

您可以在类中构建您的需求,例如输出并制作输出列表。

public class Output{
   private String str1;
   private String str2;
   private String str3;
   <geter & setter method>
}

...

ArrayList<Output> list=new ArrayList<Output>();
int i=-1; Output op =null;
while (scanner.hasNextLine()) {
     String line = scanner.nextLine();i = ++i%3;
     if(i==0){
        op = new Output();
        op.setStr1(line);
     }else if(i==1)
        op.setStr2(line);
     else
        op.setStr3(line);
}

【讨论】:

    【解决方案2】:

    我拿了你的代码并稍作修改:

    File file = new File("f://file.txt");
    
    try {
        Scanner scanner = new Scanner(file);
    
        int itemsOnRow = 0;
    
        while (scanner.hasNextLine()) 
        {
            String line = scanner.nextLine();
            System.out.print (line + " ");
    
            itemsOnRow++;
    
            if (itemsOnRow == 3)
            {
                itemsOnRow = 0;
                System.out.println ();
            }
        }
    
        scanner.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    

    你应该下次真正尝试实现它。如果你失败了但发布了你编写的代码,那么这里的人更容易帮助你。

    【讨论】:

    • 不需要写不好的代码,只要给他好的建议就可以了。
    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    相关资源
    最近更新 更多