Quebra de uma String em Strings menores

2 respostas
C

Bom dia pessoal,

Gostaria de saber se alguém sabe algum algoritmo ou até mesmo alguma opinião de como posso fazer a seguinte operação:

Pegar uma String, divir essa String em pequenas Strings de 50 bytes(levando em consideração que a última tem grande chance de ter menos de 50 bytes) e adicionar essas Strings menores em uma lista.

Alguém, por gentileza, pode me dar uma luz?

Muuuito Obrigado!

2 Respostas

E
import java.util.*;

class Quebra50 {
    public static void main(String[] args) {
        String stringao = "import java.util.*; class The3n1problem { int max; public The3n1problem (int max) { this.max = max; cl = new long [max + 1]; cl [1] = 1; } public int cycleLength (int num) { long next = num;";
        List<String> strings = new ArrayList<String>();
        int len = stringao.length();
        for (int pos = 0; pos < len; pos += 50) {
            strings.add (stringao.substring (pos, Math.min (pos + 50, len)));
        }
        System.out.println (strings);
    }
}
barenko

O entanglement já respondeu, mas… tb quero deixar minha versão a lá Regex :wink:

public class Main {
    public static void main(String[] args) throws Exception {
		String input = "import java.util.*; class The3n1problem { int max; public The3n1problem (int max) { this.max = max; cl = new long [max + 1]; cl [1] = 1; } public int cycleLength (int num) { long next = num;";

		for (String s : splitBy50(input)) {
	    	System.out.println(s);
		}
 	}

    private static String[] splitBy50(String s) {
		String key = "¤¤¤";
		return s.replaceAll("(?s)(.{1,50})", "$1" + key).split(key);
    }
}
Criado 19 de novembro de 2009
Ultima resposta 19 de nov. de 2009
Respostas 2
Participantes 3