How to convert string to integer in C# - c#

How do I convert a string to an integer in C#?

If you're sure it'll parse correctly, use
int.Parse(string)
If you're not, use
int i;
bool success = int.TryParse(string, out i);
Caution! In the case below, i will equal 0, not 10 after the TryParse.
int i = 10;
bool failure = int.TryParse("asdf", out i);
This is because TryParse uses an out parameter, not a ref parameter.

int myInt = System.Convert.ToInt32(myString);
As several others have mentioned, you can also use int.Parse() and int.TryParse().
If you're certain that the string will always be an int:
int myInt = int.Parse(myString);
If you'd like to check whether string is really an int first:
int myInt;
bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value
if (isValid)
{
int plusOne = myInt + 1;
}

int a = int.Parse(myString);
or better yet, look into int.TryParse(string)

string varString = "15";
int i = int.Parse(varString);
or
int varI;
string varString = "15";
int.TryParse(varString, out varI);
int.TryParse is safer since if you put something else in varString (for example "fsfdsfs") you would get an exception. By using int.TryParse when string can't be converted into int it will return 0.

Do something like:
var result = Int32.Parse(str);

If you are sure that you have "real" number in your string, or you are comfortable of any exception that might arise, use this.
string s="4";
int a=int.Parse(s);
For some more control over the process, use
string s="maybe 4";
int a;
if (int.TryParse(s, out a)) {
// it's int;
}
else {
// it's no int, and there's no exception;
}

4 techniques are benchmarked here.
The fastest way turned out to be the following:
y = 0;
for (int i = 0; i < s.Length; i++)
y = y * 10 + (s[i] - '0');
"s" is your string that you want converted to an int. This code assumes you won't have any exceptions during the conversion. So if you know your string data will always be some sort of int value, the above code is the best way to go for pure speed.
At the end, "y" will have your int value.

int i;
string whatever;
//Best since no exception raised
int.TryParse(whatever, out i);
//Better use try catch on this one
i = Convert.ToInt32(whatever);

bool result = Int32.TryParse(someString, out someNumeric)
This method will try to convert someString into someNumeric, and return a result depending on whether or not the conversion is successful: true if conversion is successful and false if conversion failed. Take note that this method will not throw an exception if the conversion failed like how Int32.Parse method did and instead returns zero for someNumeric.
For more information, you can read here:
https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
&
How to convert string to integer in C#

int i;
string result = Something;
i = Convert.ToInt32(result);

You can use either,
int i = Convert.ToInt32(myString);
or
int i =int.Parse(myString);

class MyMath
{
public dynamic Sum(dynamic x, dynamic y)
{
return (x+y);
}
}
class Demo
{
static void Main(string[] args)
{
MyMath d = new MyMath();
Console.WriteLine(d.Sum(23.2, 32.2));
}
}

Related

C# How to make a return function?

So i have a question. I'm trying do make a function witch returns a number, but the problem is that i can't convert int to string. My functions looks like this:
static string EnemyDmg(EnemyDmg _dmg)
{
string result = "";
int EnemyDmg
= CharAttack - EnemyDefense;
if (EnemyDmg < 1)
EnemyDmg = 4;
result = EnemyDmg;
return result;
}
but it should do this
int EnemyDmg
= CharAttack - EnemyDefense;
if (EnemyDmg < 1)
EnemyDmg = 4;
Console.WriteLine(EnemyName + " takes " + EnemyDmg + " Damage");
has anyone an idea?
PS: The 4 is just a random number.
should be static int EnemyDmg(EnemyDmg _dmg). You should return an int, and convert to string outside the function iif you need that
Anyway, to convert a String s into an int i:
int i = Int32.Parse(s);
to convert an int i into a string s
string s = i.ToString();
string s = ""+i; // more "java-like"
This question is a bit ambiguous; I'm not sure why you've done it this way.
You can convert a C# integer to a string with the .ToString() method, like this:
int a = 12;
string aString = a.ToString();
Console.WriteLine(a);
https://dotnetfiddle.net/sMC3hU
static string toStr(int intInput)
{
string str = intInput.ToString();
return str;
}
}
This code will do it for you. There is no need to use if statement as there is no any specific requirement, it will make more complicated code.
or else
you can direct use ToString parameter if there is an user input just refer to the 3rd line.

How to add two strings that are numbers? [duplicate]

This question already has answers here:
Adding numbers to a string?
(5 answers)
Closed 7 years ago.
i am looping through some nodes and getting the charge and adding them together. the charge is of type string though.
first time it loops string charge = "309",
second time it loop string charge = "38";
`Looping through list of nodes
{
saBillDetail.TotalServiceUsage += totalSvcNode.InnerText;
}
`
I would have expected that I could add them together, but they are being concatenated instead like this:
`charge + charge = '30938'`
How can I force these strings to be treated as numbers? and get output like this at the end of the loop
`charge + charge = '347'`
As people allready answered this maybe another solution
So you don't get errors
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return iOne + iTwo;
}
Or if you want a string result.
private static String AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return (iOne + iTwo).ToString();
}
EDIT:
As Alexei Levenkov stated you could/should handle exceptions.
Maybe something like this will help you during development
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
bool successParseOne = Int32.TryParse(one, out iOne);
bool successParseTwo = Int32.TryParse(two, out iTwo);
if (!successParseOne)
{
throw new ArgumentException("one");
}
else if(!successParseTwo)
{
throw new ArgumentException("two");
}
return (iOne + iTwo);
}
So when you have a wrong number you will be notified if you use try/catch
You need to parse the numbers from the strings:
string number1 = "309";
string number2 = "38";
int result = int.Parse(number1) + int.Parse(number2);
Then you can set the text equal to that string representation:
string addResult = result.ToString();
Note: Int32.Parse() will throw an exception if the format isn't correct. Consider using Int32.TryParse() for a bool way to capture an impossible parsing.
You will need to convert your strings to integer, add them and convert the result back to string:
int sum = 0;
foreach (string strNumber in strNumberCollection)
{
int number;
if (int.TryParse(strNumber, out number))
sum += number;
}
string total = sum.ToString();

Converting a string like "09335887170" to an integer

How can I convert a string like "09335887170" to an integer? Here is what I have tried:
string a = "09335887170";
int myInt;
bool isValid = int.TryParse(a, out myInt); // it returns false in this case
if (isValid)
{
int plusOne = myInt + 1;
MessageBox.Show(plusOne.ToString());
}
MessageBox.Show(a);
int stringToInt = Convert.ToInt32("09335887170"); // it returns nothing with no error
MessageBox.Show((stringToInt + 1).ToString());
int test = int.Parse(a); //it has type convertion error
MessageBox.Show((test + 1).ToString());
The maximum value of a Int32 (or only int) is 2,147,483,647
you need a UInt64 or Int64 or Long
string a = "09335887170";
Int64 myInt;
bool isValid = Int64.TryParse(a, out myInt);
if (isValid)
{
int plusOne = myInt + 1;
MessageBox.Show(plusOne.ToString());
}
result = Convert.ToInt64(value);
Look here for more info.
(Found online, im not really in c#)
that number exceeds the max int value. use a long instead.
Try this
Int64 no = Convert.ToInt64( "09335887170");

How do I convert part of a string to int in C#? [duplicate]

This question already has answers here:
Find and extract a number from a string
(32 answers)
Closed 9 years ago.
static void Main(string[] args)
{
string foo = "jason123x40";
char[] foo2 = foo.ToCharArray();
string foo3 = "";
for (int i = 0; i < foo2.Length; i++)
{
int num = 0;
Int32.TryParse(foo2[i].ToString(), out num);
if (num != 0)
{
foo3 += num.ToString();
}
}
Console.WriteLine(foo3);
Console.ReadLine();
}
So lets say I have a string called "john10smith250". The result should be "10250". However I would get "125" instead with my code.
The reason I filtered out the 0 was because I didn't want any non numeric characters to be treated as a zero.
Is there a better way to convert a part of a string into an int?
Using LINQ :
var myString = "john10smith250";
var myNumbers = myString.Where(x => char.IsDigit(x)).ToArray();
var myNewString = new String(myNumbers);
You've got a couple of good solutions that change the approach and shorten your code. For completeness, here is how you make your code work.
Your code assumes that if the num is zero, the parse has failed:
int num = 0;
Int32.TryParse(foo2[i].ToString(), out num);
if (num != 0) // This is wrong
{
foo3 += num.ToString();
}
You need to change the code like this:
int num = 0;
if (Int32.TryParse(foo2[i].ToString(), out num))
{
foo3 += num.ToString();
}
The reason your code did not work was that you ignored the return value of TryParse. It returns false if the parse fails, or true if the parse succeeds, even if the number being parsed is zero. In fact, that's the reason behind TryParse taking an out parameter (as opposed to returning the value directly, the way the Int32.Parse does).
You can solve it by using Regx
\d+ is the regex for an integer number.
So
string outputstring = Regex.Match(yourstring, #"\d+").Value;
will give you that number as a string. Int32.Parse(outputstring) will then give you the number.
or you can do like this
go through the string and use Char.IsDigit
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
{
val = int.Parse(b);
}
use :
var str= "jason123x40";
var number= str.Where(x => char.IsDigit(x)).Select(x => x);
Pretty close to what you have there...
int parseNumbersFromString(string data)
{
string number = "";
for(int i = 0; i < data.Length; ++i)
{
if(char.IsDigit(data[i]))
number += data[i];
}
return Convert.ToInt32(number);
}
*You can use index to access a char in a string
*IsDigit check if this char is a digit then append it to the string foo2 if condition is true
string foo = "jason0123x40";
string foo2 = "";
for (int i = 0; i < foo.Length; i++)
{
if (char.IsDigit(foo[i]))
foo2 += foo[i];
}
Console.WriteLine(foo2);
Console.ReadLine();
You can use a regular expression as follows:
string foo = "jason123x40";
string foo3 = Regex.Replace(foo, #"\D", "");

Difference between int CompareTo method and ordinary If condition?

I have tried the comparison for two integer values by using two types
Type 1 :
int val1 = 1;
int val2 = 2;
var returnValue = val1.CompareTo(val2);//-1 for First int is smaller.
varreturnValue = val2.CompareTo(val1);// 1 for First int is larger
varreturnValue = val1.CompareTo(val1);//0 for Ints are equal.
If(varreturnValue ==1)
{
//Success
}
else
{
//Failure
}
Type 2:
int val1 = 1;
int val2 = 2;
if (val1 < val2)
{
//return -1 //Failure
}
else if (val2 < val1)
{
//return 2 //Success
}
else
{
// return 0 // Same
}
What is the difference these methods?
Which one(type) is better for standard coding .. ?
Any difference for performance in the types ?
When I take a peek at the internals of int's CompareTo() method (using ReSharper), I see this:
public int CompareTo(int value)
{
if (this < value)
return -1;
return this > value ? 1 : 0;
}
So it would appear, in the case of an int anyway, that the CompareTo() function is doing exactly what your second example does.
If we remove the ternary operator, it looks identical to your example:
public int CompareTo(int value)
{
if (this < value)
return -1;
if (this > value)
return -1;
return 0;
}
In my opinion, the CompareTo method is good in case you need to separate the logic that checks for equality and another logic that uses the result from the comparison. In your example, when you do your code like:
int val1 = 1;
int val2 = 2;
if (val1 < val2)
{
//return -1 //Failure
}
else if (val2 < val1)
{
//return 2 //Success
}
else
{
// return 0 // Same
}
You cannot return to another function the comparison result. Here is the code extracted from msdn:
enum Comparison {
LessThan=-1, Equal=0, GreaterThan=1};
public class ValueComparison
{
public static void Main()
{
int mainValue = 16325;
int zeroValue = 0;
int negativeValue = -1934;
int positiveValue = 903624;
int sameValue = 16325;
Console.WriteLine("Comparing {0} and {1}: {2} ({3}).",
mainValue, zeroValue,
mainValue.CompareTo(zeroValue),
(Comparison) mainValue.CompareTo(zeroValue));
}
}
In this case, the comparison result is represented as an enum and can be passed between functions.
Another case is you could even serialize the comparison result over the wire as a numeric value (-1,0,1) (return value of an ajax call, for example)
There may be not much thing to do with numeric comparison like this, but as noted by Patryk Ćwiek in his comment. CompareTo may be used via interface, which can be implemented by other datatypes including your custom ones.

Categories