Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert a string with letters to int c#

this is my question:

Input: s = "4193 with words"
Output: 4193

I tryed it this way but it does not work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        int a;
         bool  tf =  int.TryParse(s,out a);
        if(tf == true)
        {
            return a;
        }
        return 0;

>Solution :

You can use this to extract only the numeric characters from the string:

string numStr = new String(s.Where(Char.IsDigit).ToArray());

Then use your existing code, but referring to numStr:

int a;
bool  tf =  int.TryParse(numStr,out a);
if (tf == true)
{
   return a;
}
return 0;

Note that if you’d like to support negative integers, you will need to adapt the first part (extracting relevant characters) accordingly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading