Reputation: 3515
I have string
string a = "234234324\r\n";
I want to parse this string into integer with losing this \r\n
part, so int
should contain only digits from string a like int b = 234234324
;
p.s. string does not necessarily contain the \r\n
part, point is that I want to use only digits from string.
I tried with Convert.ToInt32(a)
but I have error.
Upvotes: 1
Views: 117
Reputation: 32561
Try this (you need to add a reference to Microsoft.VisualBasic):
using Microsoft.VisualBasic;
class Program
{
static void Main(string[] args)
{
var a = "234234324\r\n";
int b = int.Parse(Conversion.Val(a).ToString());
}
}
Upvotes: 0
Reputation: 172438
You must use Trim
followed by Int32.TryParse
int b = Int32.TryParse(a.Trim(), out num);
Upvotes: 1
Reputation: 34846
Try this:
string a = "234234324\r\n";
string justNumbers = new String(a.Where(Char.IsDigit).ToArray());
Note: Obviously, this requires LINQ.
Now you can convert the string without fear of non-numerics being in the string, like this:
Convert.ToInt32(justNumbers);
Upvotes: 2
Reputation: 22794
int b = int.Parse(new string(a.Where(char.IsDigit).ToArray()));
Upvotes: 8
Reputation: 102753
You just need Trim
-- that removes all leading and trailing whitespace.
int b = int.Parse(a.Trim());
Upvotes: 7