We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Parsing integer from a string
Page Index Toggle Pages: 1
Parsing integer from a string (Read 1461 times)
Parsing integer from a string
Feb 23rd, 2010, 8:03pm
 
Hi all,  Smiley
I have a question about parsing data.
A string like "channel 11";
How can I parse the integer 11 from the string "channel 11" ?

thanks for your help.  
Re: Parsing integer from a string
Reply #1 - Feb 23rd, 2010, 8:24pm
 
http://processing.org/reference/split_.html
http://processing.org/reference/int_.html

String[] splitted = split("channel 11");
int eleven = int(splitted[1]);
Re: Parsing integer from a string
Reply #2 - Feb 23rd, 2010, 8:26pm
 
oh, but i guess, more useful would be if you don't know where the number is.... i would say in general one could split (if you know the number will always be surrounded by spaces), and then loop through each part of the split string such that you test each? i am not sure!
Re: Parsing integer from a string
Reply #3 - Feb 23rd, 2010, 10:07pm
 
thank you so much for your help. already solved. Have a nice day  Cheesy
Re: Parsing integer from a string
Reply #4 - Feb 23rd, 2010, 11:27pm
 
th0m: you can use a regular expression to isolate a number in a string.
Re: Parsing integer from a string
Reply #5 - Feb 24th, 2010, 2:52am
 
you can always use try/catch Wink

Quote:
int myInt;
String[] subStrings = split( "john is a happy 11 number", ' ' );


for( int i = 0; i < subStrings.length; ++i )
{
  try
  {
    myInt = int( subStrings[i] );
  }
  catch(NumberFormatException e)
  {
    // do what you want to do with it
  }

}



You can use break in try block to protect yourself in case of more then one number exists in the string. Then after the first one you quit the for loop.

Be careful with split, btw. If your string will be something like:

String[] subStrings = split( "john is a happy 11, isn't he?", ' ' );

then you won't get a number as a substring after splitting would be

"11,"

which wouldn't parse into int and would throw exception!
Re: Parsing integer from a string
Reply #6 - Feb 24th, 2010, 4:58am
 
Example with regular expression:
Code:
String sentence = "John is a happy 11, isn't he? U2.";
String[] m = match(sentence, "\\d+");
if (m != null) // Found!
{
println(m[0]);
}
Page Index Toggle Pages: 1