Problema com Strings [RESOLVIDO]

2 respostas
CondeGil

bom dias pessoal
estou com um problema num exercicio para estudo, é o seguinte:

3. Realize um método estático da classe FileUtils: public static void nSpacesBy1Tab( String pathnameIn, String pathnameOut, int n) throws FileNotFoundException, IOException que copie integralmente o conteúdo do ficheiro de texto com pathname pathnameIn para o ficheiro de texto com pathname pathnameOut, mas substituindo cada sequência de n caracteres espaço (? ?) por um carácter tab (?\t?). Por exemplo, com n=4, o texto: ?0 1 2 3 4 5 6 7 8?, seria transcrito como: ?0 1 2 3\t4\t5\t 6\t 7\t\t8?.
eu ja tentei muita coisa mas n to a conseguir dar a volta a isto, a parte da strem é facil n tem nada q saber, eu fiz o seguinte:
public static void nSpacesBy1Tab(String pathnameIn, String pathnameOut, int n)throws IOException {
		
		char tab = '	';
		FileReader fileReader = new FileReader(pathnameIn);
		BufferedReader reader = new BufferedReader(fileReader);
		String line=new String(), finalstr=new String();
		int aux=0;
		
		while((line=reader.readLine())!=null){
			for(int i=0; i<line.length(); i++){

			}
		}
	}

esta ja ai um for para mecher a String line, mas o resto n me estou a safar :S quem sober q me dê uma maozinha :P

2 Respostas

R

Acho que, em vez de percorrer a string com , é melhor usar o método String.replace():

finalstr = line.replace("    ", "\t");
CondeGil

Muito obrigado, ja nem me lembrava disso xD problema resolvido :D
caso interece a alguem...

public static void nSpacesBy1Tab(String pathnameIn, String pathnameOut, int n)throws IOException {
		
		String tab = "";
		FileReader fileReader = new FileReader(pathnameIn);
		BufferedReader reader = new BufferedReader(fileReader);
		String line=new String(), finalstr=new String();
		
		FileOutputStream fileStream = new FileOutputStream(pathnameOut);
		PrintWriter writer = new PrintWriter(fileStream);
		
		for(int i=0; i<n; i++)
			tab+=" ";
		
		while((line=reader.readLine())!=null){
			finalstr = line.replace(tab, "\t");
			writer.println(finalstr);
			writer.flush();
		}
	}
Criado 2 de maio de 2009
Ultima resposta 2 de mai. de 2009
Respostas 2
Participantes 2