Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strip/Convert Alphanumeric to Int

Status
Not open for further replies.

Exie

Programmer
Sep 3, 2003
156
AU
Hi,

I need to convert an Alphanumeric (eg. "ABC123") into an Integer (eg. "123").

I've tried using :
int x = Integer.valueOf(str).intValue()

but I get an exception. I cant find anything that will handle the alpha's in my string, so I presume I need to strip them out. Any suggestions on how I could get all this to work ?
 

.... I was considering using Regx to process my string, I dont know if this would work, or is even possible!
 
This code should do what you need it to do.

public int returnNumbers(String foo)
{
char charArray[] = new char[0];
String strReturn="";
if (foo.length() > 0) // must have 1 digit at least
{
charArray = new char[foo.length()]; //instatiate char array.
foo.getChars(0, (foo.length()), charArray, 0); //put string into char array
for (int intIndex = 0; intIndex < title.length(); intIndex++)
{
if (Character.isDigit(charArray[intIndex]) == true)
{
//if it's a number add it to the string.
strReturn = strReturn + charArray[intIndex];
}
}
return Integer.parseInt(strReturn); //return the integer value of the string.
}
return 0; //return 0 if there was a 0 length argument.
}
 
Replace:
for (int intIndex = 0; intIndex < title.length(); intIndex++)

with:
for (int intIndex = 0; intIndex < foo.length(); intIndex++)

If you see anything else in there that says "title" change it to "foo".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top