Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing Strings in C#

Status
Not open for further replies.

raghu75

Programmer
Nov 21, 2000
66
0
0
IN
Hi,
I have to parse a few strings in C#. The strings are AlphaNumeric.i.e. they contain characters and numerals.
I want to pick only the numerals in the string.
is there any way to do it???

ex: string MyStr = "ragh1210";
I want to extract 1210 from the above.How can this be done??

Rgds,
raghu
 

You can use some of the Char methods to parse the string(
Char.IsLetter, Char.IsNumber, Char.IsPunctuation, Char.IsSeparator, Char.IsWhiteSpace....).
And a short example:

String s = "123sgjhfg";
String s1 = "";
for(int i=0; i < s.Length;i++)
{
if(Char.IsNumber(s,i))
{
s1 = s1 + s;
}
}
 
Even better if you use StringBuilder instead of String for s1.

String s = &quot;123sgjhfg&quot;;
String result;
StringBuilder s1 = new StringBuilder();
for(int i=0; i < s.Length;i++)
{
if(Char.IsNumber(s,i))
{
s1 += s;
}
}
result = s1.ToString();


It has better memory usage.
String creates a new object each time you append something to it.
StringBuilder does not.

Larsson
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top