Java:如何用空格分割“st r n n g”替换.txt文件中的“string”

时间:2017-03-10 21:34:43

标签: java.util.scanner filewriter

我正在寻找重写我的整个.txt文件的数字,例如302340372048725280至3 0 2 3 4 0 3 7 2 0 4 8 7 2 5 2 8 0.我该怎么做?

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class IntSeparator {

    public static void main(String[] args) throws IOException {
        Scanner scanner;
        try {
            scanner = new Scanner(new File("src/extremePuzzles.txt"));

            PrintWriter spacer = new PrintWriter(new FileWriter("src/extremePuzzles.txt", true));

            while (scanner.hasNext()) {
                String puzzle = scanner.next();
                System.out.println(puzzle);

                String splitted = puzzle.replace("", " ").trim();
                System.out.println(splitted);

                spacer.print(splitted);
            }

        } catch (FileNotFoundException e) {
            System.out.println("file not found!");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

简单的字符串处理可以如下工作

public class Str{

    public static void main(String args[]){
    String str = "302340372048725280";

    String temp = "";
    int i=0;
    int len = str.length();
    while(len>0){
        temp+=str.charAt(i);
        i++;
        len--;
        temp+=" ";
    }

   System.out.println(temp);

   }
}

您可以根据需要使用此代码!

答案 1 :(得分:-1)

是的,这应该有效。或者你可以做到

String splitted = puzzle.replaceAll(".(?=.)", "$0 ");

基本上它说"用字符本身替换所有字符(除了最后一个字符)后跟一个空格"。 礼貌:Add spaces between the characters of a string in Java?