Alguém me pode dizer o que significa:

6 respostas
P

Tenho esta dúvida e não percebo o que faz o seguinte código:

return indiceInicio < indiceFim ? texto.substring(indiceInicio, indiceFim + 1) : “”;

Trata-se de uma rotina para limpar os espaços, ex: " Bom dia Pessoal " ---------> “Bom dia Pessoal” ( ou seja, só retira os espaços antes e depois da frase em si)

A rotina completa é:

public static String removeEspacos(String texto){

int indiceInicio = 0;
	while(indiceInicio < texto.length() && texto.charAt(indiceInicio) == ' ' ){
		indiceInicio ++;
	}
	
	int indiceFim = texto.length() - 1;
	while(indiceFim >= 0 && texto.charAt(indiceFim) == ' ' ){
		indiceFim --;
	}
	
	return indiceInicio < indiceFim ? texto.substring(indiceInicio, indiceFim + 1) : "";
}</blockquote>

6 Respostas

xandevieira

Isto

return indiceInicio < indiceFim ? texto.substring(indiceInicio, indiceFim + 1) : "";

é o mesmo que isto

if(indiceInicio < indiceFim){
return texto.substring(indiceInicio, indiceFim + 1)
} else {
return "";
}
C

Para retirar os espaços do inicio e fim da string, use o método trim().

Por exemplo:

String var = " Bom dia Pessoal ";

System.out.println(var.trim());

Até mais.

douglaskd

pra clarerar um pouco mais

return indiceInicio < indiceFim ? texto.substring(indiceInicio, indiceFim + 1) : "";

indiceInicio menor que indiceFim? se sim retorne texto.substring(indiceInicio, indiceFim + 1) senão retorne “”

P
avsouza:
Isto
return indiceInicio < indiceFim ? texto.substring(indiceInicio, indiceFim + 1) : "";
é o mesmo que isto
if(indiceInicio < indiceFim){
return texto.substring(indiceInicio, indiceFim + 1)
} else {
return "";
}

Eu percebi praticamente tudo, obrigadão:D. Só não entendo uma coisa :X.

Caso efectue o "else", o que é devolvido? "" ? É uma String vazia?

xandevieira

Isso

marcelo.bellissimo

Só pra constar, isso se chama “Operador Ternário”, ok?

condição ? valor_para_true : valor_para_false;

Criado 1 de dezembro de 2010
Ultima resposta 1 de dez. de 2010
Respostas 6
Participantes 5