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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Specific question regarding Strings 2

Status
Not open for further replies.

thelordoftherings

Programmer
May 16, 2004
616
IL
Hello,

Lets say I have a certain String called myString which contains letters, numbers and white spaces.
Can someone please show me how do I find the first occurrence of a character inside the string of a character which represents a number?
 
You could convert the String to an array of chars, and then loop the array, attempting to parse the character to an integer or double.

--------------------------------------------------
Free Database Connection Pooling Software
 
And here is a strange thing:
I tried your method: int in = new Integer(tempArray).intValue(); and it converts all the chrs to int even if the char is not an integer, how could this be?
 
Every char has an int value - so you can't do it like that.
You'd need to do it something like :

Code:
try {
  // force the char to a string, and try to parse it
  Double.parseDouble(tempArray[i] +"");
  // it is a number
} catch (NumberFormatException nfe) {
   // not a number
}

--------------------------------------------------
Free Database Connection Pooling Software
 
Maybe too much time consuming for long Strings

Try this:

Code:
String myString = "What1So2Ever";
int len = myString.length;

for (int posFirstDigit = 0;posFirstDigit<len;posFirstDigit++)
  if (Character.isDigit(myString.charAt(posFirstDigit)))
    break;

Cheers,

Dian
 
Another (probably inferior) alternative, using regexps:
Code:
String str = "bfdasf fds 3 fads";
Matcher m = Pattern.compile( "\\d" ).matcher( str );
if ( m.find() ) {
   System.out.println( "First digit is at position: " + m.start() );
}
else {
   System.out.println( "No matches" );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top