2017-03-10 1 views
-1

Je cherche à réécrire tout mon fichier .txt de nombres, par ex. 302340372048725280 à 3 0 2 3 4 0 3 7 2 0 4 8 7 2 5 2 8 0. Comment puis-je faire cela?Java: Comment remplacer "chaîne" dans le fichier .txt par un espace "s t r i n g"

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!"); 
     } 
    } 
} 

Répondre

-1

Oui, cela devrait fonctionner. Ou vous pouvez faire

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

Fondamentalement, il dit: « Remplacer tous les caractères (sauf le dernier) avec le caractère lui-même suivi d'un espace ». Avec l'aimable autorisation : Add spaces between the characters of a string in Java? traitement de chaîne simple

+0

Mais cela ne fonctionne pas, il n'écrit pas la chaîne fractionnée dans mon fichier .txt! spacer.print (divisé); ne fonctionne pas – Tai

+0

c'est plutôt étrange, vous pouvez réinventer la roue puis, essayez l'addition manuelle de l'espace en faisant une boucle dans la séquence et en ajoutant un espace entre les deux jusqu'à ce que votre compte atteigne le dernier char – Olagsfark

0

peut fonctionner comme ci-dessous

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); 

    } 
} 

Vous pouvez utiliser ce code selon vos besoins!