Campo string...retirar numeros [Resolvido]

13 respostas
T

Pessoal,

Estou com uma duvida num campo String, pois preciso “subtrair” dele um numero

a parte onde esta montada:

farmacia.setNossoCodigo(request.getParameter("idCampo"));

o resultado disso é 234560…mas só posso ter o campo com 5 numeros( e esta com 6)

Tem como eu subtrair a preimra casa aqui?

brigada

13 Respostas

A

O substring ajuda com essa questão

String a = "a5451a5";
String g = a.substring(1, 2); //me traz 1 char na 2 posição
		
System.out.println(g); //retorna o 5

Tá aqui o link da API
API

— Somente sobre substring (recortei) —
substring

public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Examples:

“unhappy”.substring(2) returns “happy”
“Harbison”.substring(3) returns “bison”
“emptiness”.substring(9) returns “” (an empty string)

Parameters:
beginIndex - the beginning index, inclusive.
Returns:
the specified substring.
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
substring

public String substring(int beginIndex,
int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Examples:

“hamburger”.substring(4, 8) returns “urge”
“smiles”.substring(1, 5) returns “mile”

Parameters:
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
Returns:
the specified substring.
Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

ViniGodoy

Acho que antes de vc “cortar” a String, você tem que se perguntar pq está vindo dígitos a mais.

É melhor corrigir o erro, e não o sintoma.

T

andre,

obrigada pela ajuda. Eu só nao estou consguindo acoplar o substring na linha abaixo(problema de sintaxe)

farmacia.setNossoCodigo(request.getParameter("idCampo"));

andre.froes:
O substring ajuda com essa questão

String a = "a5451a5";
String g = a.substring(1, 2); //me traz 1 char na 2 posição
		
System.out.println(g); //retorna o 5

Tá aqui o link da API
API

— Somente sobre substring (recortei) —
substring

public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Examples:

“unhappy”.substring(2) returns “happy”
“Harbison”.substring(3) returns “bison”
“emptiness”.substring(9) returns “” (an empty string)

Parameters:
beginIndex - the beginning index, inclusive.
Returns:
the specified substring.
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
substring

public String substring(int beginIndex,
int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Examples:

“hamburger”.substring(4, 8) returns “urge”
“smiles”.substring(1, 5) returns “mile”

Parameters:
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
Returns:
the specified substring.
Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

vitimnunes

se for pra remover todos os numeros…

String misto = new String( "ab12h4l8cd5" );
String resultado = new String();

for( int i = 0; i < misto.length; i++ ) {
  Integer aux;
  
  try {
    aux = Integer.parseInt( misto.charAt( i ) );
  } catch( Exception e ) {
    aux = null;
  }

  if( aux != null ) {
    resultado = resultado.concat( String.valueOf( aux ) );
  }
}

int result = Integer.parseInt( resultado );
System.out.println( result );
evaristo.blog

Se for só retirar utiliza substring(), se for para arredondar ja nao é tao trivial mas ainda assim simples

Cumprimentos,
João (http://www.evaristotenscadisto.com)

A
public static void main(String[] args) {
		
		String texto = "5sddf5as454das5d4asd54w84ad84g";  
		String numeros = "";  
		for (int i = 0; i < texto.length(); i++) {  
		  
		   if (Character.isDigit(texto.charAt(i)) == true){  
		       numeros = numeros+texto.charAt(i);   
		   }  
		}  
		long total = Long.parseLong(numeros);  
		System.out.println(total);
		
	}

essa é uma outra opção ^^

ViniGodoy

Volto a repetir. Ao invés de “cortar” a String, é melhor corrigir o problema real!!!

Por que a String está vindo com um dígito à mais? Não deveria estar vindo certa?

Não mascare bugs! Rastreie a origem do problema e corrija-a!

Naruffy

Como vc estah recebendo um parâmetro creio q esta seja uma aplicação Web.

Não seria melhor ao invés de você remover um caracter no lado servidor vc fazer uma validação do campo que o usuário entra com esse digitos no lado client?

caso seja um campo input basta colocar o atributo maxlength=“5” para que o usuário não posso digitar mais de 5 caracteres

T

Vini, obrigada pela ajuda…

Nao estou “mascarando” bugs. Existe uma aplicacao que faz uma simulacao com um aplicativo de banco, este por sua vez nao aceita mais que 5 casas, no entando, os numeros geraros ja estao vindo com 6 casas visto que os pedidos estao em mais de 100.000.

ViniGodoy:
Volto a repetir. Ao invés de “cortar” a String, é melhor corrigir o problema real!!!

Por que a String está vindo com um dígito à mais? Não deveria estar vindo certa?

Não mascare bugs! Rastreie a origem do problema e corrija-a!

ViniGodoy

Ah bom, entendi. É que é um erro comum entre os iniciantes na programação tentarem corrigir o sintoma, não a causa. E com isso acabam mascarando bugs e se complicando. Como esse é o fórum de Java Básico, pensei que fosse seu caso também.

De qualquer forma, para cortar a String basta fazer:

final int TAM = 5;

String idCampo = request.getParameter("idCampo");
if (idCampo.length > TAM) {
   idCampo = idCampo.substring(TAM - idCampo.length);
}
T

Oi..

eu utilizei a logica que falou, mas ele acusou este arro:

String index out of range: -1

linha do codigo
final int TAM = 5;

String idField = request.getParameter("idField");
if (idField.length() > TAM) {
   idField = idField.substring(TAM - idField.length());
}
ViniGodoy:
Ah bom, entendi. É que é um erro comum entre os iniciantes na programação tentarem corrigir o sintoma, não a causa. E com isso acabam mascarando bugs e se complicando. Como esse é o fórum de Java Básico, pensei que fosse seu caso também.

De qualquer forma, para cortar a String basta fazer:

final int TAM = 5;

String idCampo = request.getParameter("idCampo");
if (idCampo.length > TAM) {
   idCampo = idCampo.substring(TAM - idCampo.length);
}
claudiom

tatiana.sch:
eu utilizei a logica que falou, mas ele acusou este arro: String index out of range: -1

linha do codigo

final int TAM = 5;

String idField = request.getParameter("idField");
if (idField.length() > TAM) {
   idField = idField.substring(TAM - idField.length());
}

atenção para assinatura do método substring… ele recebe um indice inicial OU um indice inicial e final…

como você quer restrigir o tamanho máximo utilize

idField = idField.substring(0, TAM);
T

Obrigada a todos voces !

Vini , Claudio brigadinha pela ajuda !!

abs

Criado 9 de julho de 2010
Ultima resposta 12 de jul. de 2010
Respostas 13
Participantes 7