Converting Strings to Integers with Apex
For one of our projects, we need to pass an integer to a function. Unfortunately, the integer is stored in a text field that is manually populated by the user. This means that it’s possible that some letters or other characters get put in the field in addition to the number we’re interested in. We know that you can do this with a regular expression but that’s kinda complex and above the heads of most of our readers. So here’s a simple way to do it via Apex that everyone should be able to follow:
Set<String> validChars = new Set<String>{'0','1','2','3','4','5','6','7','8','9'};
String mixedText = '123xyz';
String numbersOnly = '';
for (Integer i=0; i<mixedText.length(); i++)
{
if ( validChars.contains( mixedText.substring(i,i+1)) )
{
numbersOnly += mixedText.substring(i,i+1);
}
}
