Ho una stringa lunga che devo analizzare in una matrice di stringhe che non superino i 50 caratteri di lunghezza. La parte delicata di questo per me è assicurarsi che la regex trovi l'ultimo spazio bianco prima di 50 caratteri per fare una pausa netta tra le stringhe poiché non voglio che le parole vengano tagliate.Suddividere il testo dopo una lunghezza specificata ma non rompere le parole usando i grails
public List<String> splitInfoText(String msg) {
int MAX_WIDTH = 50;
def line = [] String[] words;
msg = msg.trim();
words = msg.split(" ");
StringBuffer s = new StringBuffer();
words.each {
word -> s.append(word + " ");
if (s.length() > MAX_WIDTH) {
s.replace(s.length() - word.length()-1, s.length(), " ");
line << s.toString().trim();
s = new StringBuffer(word + " ");
}
}
if (s.length() > 0)
line << s.toString().trim();
return line;
}
fornire il proprio input e output atteso? – anubhava
elenco pubblico splitInfoText (String msg) { \t \t int MAX_WIDTH = 50; \t \t \t \t linea def = [] \t \t \t \t String [] parole; \t \t \t msg = msg.trim(); \t \t \t \t words = msg.split (""); \t \t \t \t StringBuffer s = new StringBuffer(); \t \t \t \t words.each {parola -> \t \t \t \t \t s.append (parola + " "); \t \t \t \t \t \t se (s.length()> MAX_WIDTH) { \t \t \t \t \t \t \t s.replace (s.length() - word.length() - 1, s.length (), ""); . \t \t \t \t \t \t \t \t linea << s.toString() trim() \t \t \t \t \t \t \t \t s = new StringBuffer (word + " "); \t \t \t \t \t \t \t} \t \t \t \t \t} \t \t \t \t se (s.length()> 0) \t \t \t \t \t linea << s.toString().trim() \t \t \t \t \t linea di ritorno; \t \t \t} –
Nimmy
@Nimmy: ho tentato di inserire il codice nel corpo principale della domanda, ma sembrerà molto meglio se modifichi la tua domanda e inserisci il codice. – PearsonArtPhoto