Como cortar uma string e colocar (...) no final

3 respostas
jason_bourne

Alguem sabe como cortar uma string +/- dessa forma:

public String cortaString(String stringAntiga,int numCaract){
String novaString="",cortado="";
if(stringAntiga.length() >= numCaract){
.
.
.
novaString = cortado+"...";
}else{
novaString = stringAntiga;
}

return novaString;
}

3 Respostas

marcioa1

jason

novaString = stringAntiga.substring(0,numCarac+1) + “…”

Márcio

B

Olá,
Na verdade vc terá que criar uma outra String e jogar os caracteres que vc quer manter, com isso vc concaterna outra String com "…

Wanderley2k

jason_bourne,

Existe várias formas de resolver isto:
// Caso texto não tenha nada, será gerado um campo vazio
if (texto == null) {
	texto = "";
}

// Caso texto seja maior que a coluna
if (texto.length() > tamanhoDaColuna) {
	texto = texto.substring(0, tamanhoDaColuna - 3);
	texto = texto + "...";

	return texto;
}

Para melhorar um pouco a resposta. Eu fiz uma classe que formatar campos para ficarem no estilo dos relatórios do Itaú. Corta no tamanho N e preenche de espaço. Está me servindo em alguns relatórios que tenho que fazer em puro ASCCI.

package br.com.centauro.utilitario;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * FormatarCampo.java 07/07/2005
 * 
 * @author Thadeu de Russo e Carmo
 * @author Wanderley Guimarães
 * 
 * (2005) Centauro Portões
 */

public class FormatarCampo {
	public static final int ALINHAR_DIREITA = 1;

	public static final int ALINHAR_ESQUERDA = 2;

	/**
	 * Caso o texto tenha tamanho menor que o tamanho da coluna então preenche
	 * com espaços, caso contrario corta o texto e colocar "..." para indicar
	 * que foi cortado
	 * 
	 * @param texto
	 *            Texto que será processado
	 * @param tamanhoDaColuna
	 *            Tamanho da coluna que o texto deve ficar
	 * @param alinhamento
	 *            Posicao da coluna que o texto deve ficar
	 * @return Texto do tamanho da coluna
	 */
	public static String tabular(String texto, int tamanhoDaColuna,
			int alinhamento) {
		// Caso texto não tenha nada, será gerado um campo vazio
		if (texto == null) {
			texto = "";
		}

		// Caso texto seja maior que a coluna
		if (texto.length() > tamanhoDaColuna) {
			texto = texto.substring(0, tamanhoDaColuna - 3);
			texto = texto + "...";

			return texto;
		}

		StringBuffer sb = new StringBuffer(texto);

		if (alinhamento == FormatarCampo.ALINHAR_ESQUERDA) {
			while (sb.length() < tamanhoDaColuna)
				sb.append(' ');
		} else {
			while (sb.length() < tamanhoDaColuna)
				sb.insert(0, ' ');
		}

		return sb.toString();
	}

	public static String tabular(int numero, int tamanhoDaColuna,
			int alinhamento) {
		return tabular(numero + "", tamanhoDaColuna, alinhamento);
	}

	public static String tabular(double numero, int numeroDeCasasDecimais,
			int tamanhoDaColuna, int alinhamento) {

		String numeroTratado = NumberFormat.getInstance().format(numero);
		return tabular(numeroTratado, tamanhoDaColuna, alinhamento);
	}

	public static String tabular(Date data, int tamanhoDaColuna, int alinhamento) {
		if (data == null) {
			return tabular("", tamanhoDaColuna, alinhamento);
		}

		return tabularData(data, tamanhoDaColuna, alinhamento);
	}

	public static String tabularData(Date data, int tamanhoDaColuna,
			int alinhamento) {

		if (data == null) {
			return tabular("", tamanhoDaColuna, alinhamento);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		String dataFormatada = sdf.format(data);

		return tabular(dataFormatada, tamanhoDaColuna, alinhamento);
	}

	public static String tabularHora(Date hora, int tamanhoDaColuna,
			int alinhamento) {

		if (hora == null) {
			return tabular("", tamanhoDaColuna, alinhamento);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		String horaFormatada = sdf.format(hora);

		return tabular(horaFormatada, tamanhoDaColuna, alinhamento);
	}

	public static void main(String[] args) {
		System.out.println(tabularHora(new Date(), 20,
				FormatarCampo.ALINHAR_DIREITA));
	}
}

E se estiver usando java5 seria ótimo estudar:
[url]http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html#printf(java.util.Locale,%20java.lang.String,%20java.lang.Object...)[/url]
[url]http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html#printf(java.lang.String,%20java.lang.Object...)[/url]

Acho que seria isto ae! 8)

Criado 20 de julho de 2005
Ultima resposta 20 de jul. de 2005
Respostas 3
Participantes 4