using System;
using System.Text;
using System.Text.RegularExpressions;
namespace Program
{
public class App
{
static void Main(string [] args)
{
string strtemp ="AB324hgdf89dfg";
string strpart;
Nullable<int> npart;
SplitLettersAndNumbers(strtemp,out strpart,out npart);
Console.WriteLine("{0} : {1} - {2}",strtemp,strpart,npart);
}
/// <summary>
/// This method extracts all numerals and alphabets from a given string
/// </summary>
/// <param name="instr">String input</param>
/// <param name="strpart">all alphabets as string</param>
/// <param name="intpart">all numerals as string</param>
/// <returns>return if success else false<returns>
public static bool SplitLettersAndNumbers(string instr, out string strpart, out Nullable<int> intpart)
{
string strtemp = null; //buffer to hold letters
string nstrtemp = null;//buffer to hold numbers
if (instr == null) // invalid option
{
strpart = null;
intpart = null;
return false;
}
string[] m1 = Regex.Split(instr, @"\d");//All letters
string[] m2 = Regex.Split(instr, @"\D");//All numbers
//Concatenate all strings
StringBuilder sb = new StringBuilder(instr.Length);
foreach (string si in m1)
{
//Do extra processing if needed
sb.Append(si);
}
strtemp = sb.ToString();
//Concatenate all Numbers.
foreach (string si in m2)
{
//Do extra processing if needed
nstrtemp += si;
}
//Update out parameter for letters
if (strtemp != "")
{
strpart = strtemp;
}
else
{
strpart = null;
}
//Update out parameter for numbers
if (nstrtemp != "")
{
intpart = int.Parse(nstrtemp);
}
else
{
intpart = null;
}
return true;
}
}
}
No comments:
Post a Comment