How do i return integers from a string ?
- by kannan.ambadi
Normal
0
false
false
false
EN-US
X-NONE
X-NONE
MicrosoftInternetExplorer4
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
Suppose you are passing a
string(for e.g.: “My name has 1 K, 2 A and 3 N”) which may contain
integers, letters or special characters. I want to retrieve only numbers from
the input string. We can implement it in many ways such as splitting the string
into an array or by using TryParse method. I would like to share another idea,
that’s by using Regular expressions. All you have to do is, create an instance
of Regular Expression with a specified pattern for integer. Regular expression
class defines a method called Split, which splits the specified input
string based on the pattern provided during object initialization.
We
can write the code as given below:
public static
int[] SplitIdSeqenceValues(object combinedArgs)
{
var _argsSeperator = new
Regex(@"\D+",
RegexOptions.Compiled);
string[] splitedIntegers =
_argsSeperator.Split(combinedArgs.ToString());
var args = new int[splitedIntegers.Length];
for (int i = 0;
i < splitedIntegers.Length; i++)
args[i] = MakeSafe.ToSafeInt32(splitedIntegers[i]);
return args;
}
It
would be better, if we set to RegexOptions.Compiled so that the regular expression will have
performance boost by faster compilation.
Normal
0
false
false
false
EN-US
X-NONE
X-NONE
MicrosoftInternetExplorer4
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
Happy Programming :))