Tuesday, July 19, 2022

[FIXED] how to convert a string with letters to int c#

Issue

this is my question:

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

I tryed it this way but it does not work

        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.



Answered By - wohlstad
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.