'how to convert a string with letters to int c# [duplicate]
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 1:[1]
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.
Solution 2:[2]
i think you search something like this?
string input = "1234 words";
var outputnumber = Convert.ToInt32(Regex.Match(input, @"\d+").Value);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wohlstad |
| Solution 2 | Martin Bartolomé |
