PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 19, 2022

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

 July 19, 2022     c#, integer, string     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing