Skip to content

Instantly share code, notes, and snippets.

@vertigra
Last active March 22, 2017 23:30
Show Gist options
  • Select an option

  • Save vertigra/52f037ad4524748bfc193027974ca77c to your computer and use it in GitHub Desktop.

Select an option

Save vertigra/52f037ad4524748bfc193027974ca77c to your computer and use it in GitHub Desktop.
Конвертация string в int (C#)

Конвертация string в int (C#)

Конспект

//
// int.Parse(string s)
//
class Program
{
    static void Main(string[] args)
    {
        string str1="9009";
        string str2=null;
        string str3="9009.9090800";
        string str4="90909809099090909900900909090909"; 
        int finalResult;
        finalResult = int.Parse(str1); //success
        finalResult = int.Parse(str2); // ArgumentNullException
        finalResult = int.Parse(str3); //FormatException
        finalResult = int.Parse(str4); //OverflowException 
    }
}
//
// Convert.ToInt32(string s)
//
class Program
{
    static void Main(string[] args)
    {
        string str1="9009";
        string str2=null;
        string str3="9009.9090800";
        string str4="90909809099090909900900909090909"; 
        int finalResult;
        finalResult = Convert.ToInt32(str1); // 9009
        finalResult = Convert.ToInt32(str2); // 0
        finalResult = Convert.ToInt32(str3); //FormatException
        finalResult = Convert.ToInt32(str4); //OverflowException 
    }
}
//
// Convert.ToInt32(string s)
//
class Program
{
    static void Main(string[] args)
    {
        string str1="9009";
        string str2=null;
        string str3="9009.9090800";
        string str4="90909809099090909900900909090909"; 
        int finalResult;
        bool output;
        output = int.TryParse(str1,out finalResult); // 9009
        output = int.TryParse(str2,out finalResult); // 0
        output = int.TryParse(str3,out finalResult); // 0
        output = int.TryParse(str4, out finalResult); // 0 
    }
}

Что бы возвращался 0, если в строке отсутствуют цифры, небольшое расширение:

public static int ParseString(this string s)
{
    int result;
    return int.TryParse(s, out result) ? result : 0;
} 

и тест к нему (который проходит):

[Test]
public void ParseString()
{
    const string str1 = "9009";
    const string str2 = null;
    const string str3 = "9009.9090800";
    const string str4 = "90909809099090909900900909090909";
    const string str5 = "test";
    const string str6 = "тест";

    Assert.AreEqual(str1.ParseString(), 9009);
    Assert.AreEqual(str2.ParseString(), 0);
    Assert.AreEqual(str3.ParseString(), 0);
    Assert.AreEqual(str4.ParseString(), 0);
    Assert.AreEqual(str5.ParseString(), 0);
    Assert.AreEqual(str6.ParseString(), 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment