简体   繁体   English

C#中的wtol等价物

[英]wtol equivalent in C#

I am translating some code from C++ to C# and there is a function wtol which takes a string input and outputs an integer. 我正在将一些代码从C ++转换为C#,并且有一个函数wtol,它接受一个字符串输入并输出一个整数。 Specifically, it takes version string 6.4.0.1 and converts that to 4. How do I do that in C#? 具体来说,它需要版本字符串6.4.0.1并将其转换为4.我如何在C#中执行此操作? I tried convert.toInt32 but it failed miserably. 我试过convert.toInt32但它失败了。

Try this (Assuming you have a number between first and second dot): 试试这个(假设你在第一个和第二个点之间有一个数字):

string myString = "6.4.0.1";

int myInt = Convert.ToInt32(myString.Split('.')[1]);

Bit safer method would be (Assuming at least one dot in the string): 比较安全的方法是(假设字符串中至少有一个点):

int myInt = 0;
int.TryParse(myString.Split('.')[1], out myInt);

Safest method would be: 最安全的方法是:

int myInt = 0;
string[] arr = myString.Split('.');

if(arr.Length > 1 && int.TryParse(arr[1], out myInt))
{
   //myInt will have the correct number here.
} 
else
{
   //not available or not a number
}

You could use (requires .Net 4.0 or higher) 你可以使用(需要.Net 4.0或更高版本)

Version.Parse("6.4.0.1").Minor

This will work pre .Net 4.0 这将在.Net 4.0之前工作

new Version("6.4.0.1").Minor

Use this assuming that you will ALWAYS have a format that is XXXX 假设您将始终具有XXXX格式,请使用此选项

var test = "6.4.0.1";
var parts = test.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
int result = int.Parse(parts[1]);

I would suggest to use TryParse instead of just Parse , in case you are taking the version number from a not trusted source. 我建议使用TryParse而不仅仅是Parse ,以防你从不受信任的来源获取版本号。

var versionString = "6.4.0.1";
Version version;
if (Version.TryParse(versionString, out version))
{
    // Here you get your 4
    Debug.WriteLine("The version Integer is " + version.Minor);  
}
else
{
    // Here you should do your error handling
    Debug.WriteLine("Invalid version string!"); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM