What function is to be used in java so as to print the integer value of a string.
Please explain, maybe with the help of an example.
Example String:
String str = new String("HELLO");
What function is to be used in java so as to print the integer value of a string.
Please explain, maybe with the help of an example.
Example String:
String str = new String("HELLO");
If you want to find say the ASCII integer representation of an entire string and print that out you could use the String.charAt(..) method.
public class test
{
public static void main( String argv[] )
{
String str = new String("HELLO");
int age = 0;
for( int i = 0; i < str.length(); i++ ) { // Loop through the string
age += (int) str.charAt(i); // Add the current character's int representation to the age.
System.out.println( "Character: " + str.charAt(i) + " Integer value: " + (int)str.charAt(i) );
}
System.out.println( "Age: " + age );
}
}
Corrisponding output:
Character: H Integer value: 72
Character: E Integer value: 69
Character: L Integer value: 76
Character: L Integer value: 76
Character: O Integer value: 79
Age: 372
You mean convert a String into an integer?
You can do:
int val = Integer.parseInt(str);
One of the two functions:
Integer.valueOf(num); //returns Integer (Object)
Integer.parseInt(num); //returns int (primitive)
are what you want. Docs: parseInt, valueOf. However, it may often throw an exception, which you may not want. I often use:
/** returns int value or null if invalid */
public static Integer intOf(String num) {
if (num == null) return null;
try {
return Integer.valueOf(num);
} catch (NumberFormatException e) {
return null;
}
}
Try
String inputStr = "the age is 44";
String patternStr = "[0-9]+"; //or "([0-9]+)" ?
// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();
if (matchFound) {
// System.out.println(matcher.groupCount());
return matcher.group(0);
} else {
return null;
}
(from http://www.exampledepot.com/egs/java.util.regex/Group.html )