View Full Version : JAVA problem


grasshopper
09-01-03, 07:32 PM
Can any of you IT folk help me with this query.

I have a str Variable which is holding a number that the user inputs.
This number is used to query a database.

This works fine providing the user enters the number as a spaceless string. eg 1234567890. Unfortunatley there are the times that it will be entered in 3 3 4 format ie. 123 456 7890.

Before this number is passed through to the database it needs to be trimmed to a spaceless string. I know .trim() will trim spaces at the beginning and end of a string but i need to be able to remove spaces anywhere in the string.

Does anybody know how this can be done. .


Thanks in advance..

Hoppy

Wanderer
09-01-03, 08:57 PM
Seems removing spaces and dashes would be a common Java programming requirement to handle credit card info (4-4-4-4) and ID numbers *(as in US Social Security Numbers 3-2-4).

grasshopper
09-01-03, 11:44 PM
Wandy. thanks. I found 2 possible ways of doing it now. was just in a fix earlier. but all sorted.. Cheers

EviliO
10-01-03, 12:29 AM
hmmm can you explain how did you do it or what function did you use hopper?

grasshopper
10-01-03, 02:32 PM
yup no worries.
First way round i round was somewhat long winded but here it is anyway.

String temp = strNHSnumber.trim();
StringBuffer sb = new StringBuffer(temp);
for(int i= sb.length() - 1;i > -1;i--){
char c = sb.charAt(i);
if (c == ' '){
sb.deleteCharAt(i);
}
}
NHSnum = sb.toString();


The first line is not totally necassary it trims any spaces that may be at the beginning or end of the string.strNHSnumber
StringBuffer allows the String to be Manipulated
The Loop searches through the length of the string looking for spaces and deletes them
then the result is casted back into a regular string.

like i said long winded

I later found a much more efficient method. i had not heard of this command until then

String NHSnum = strNHSnumber.replaceAll(" ","");

This does exactly the same thing in one line. it searches for all occurences of " " (space) and replaces them with "" (null).

this command can be used to replace any type of character in a string..

Hope that helps.

Hoppy

Wanderer
10-01-03, 08:24 PM
NHSnum = National Health Service Corps field strength: physicians, dentists, nurse practitioners, certified nurse midwives and physician assistants ?

Quick Silver
31-01-03, 01:51 PM
another way to do that is using the tokenizer if you are reading from a file, and then just use the + sign to join the tokens together. Your way is probably easier though.