是否有相当于到C的的atoi功能的.NET? [英] Is there a .NET equivalent to C's atoi function?

查看:118
本文介绍了是否有相当于到C的的atoi功能的.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的字符串:

If I have a string like:

"26 things"

我想将其转换为26。我只想在字符串的开头的整数。

I want to convert it to 26. I just want the integer at the beginning of the string.

如果我使用C,我只是使用atoi功能。但我似乎无法找到任何的.NET等价。

If I was using C, I'd just use the atoi function. But I can't seem to find anything equivalent in .NET.

什么是抓住从一个字符串的开始?

What's the easiest way to grab the integer from the beginning of a string?

编辑:我很抱歉,我是不明确的。即寻找一个空格字符的字符串中的答案,将工作在许多情况下(甚至可能是我的)。我希望的是与atoi等同于.NET。答案也应该包含26things字符串工作。谢谢你。

I'm sorry I was ambiguous. The answers that look for a space character in the string will work in many circumstances (perhaps even mine). I was hoping for an atoi-equivalent in .NET. The answer should also work with a string like "26things". Thanks.

推荐答案

这应该工作(编辑忽视在字符串的开头空格)

This should work (edited to ignore white-space at the begining of the string)

int i = int.Parse(Regex.Match("26 things", @"^\s*(\d+)").Groups[1].Value);

如果你担心检查,如果有一个值,你可以做以下给你一个-1值如果在字符串的开头没有整数。

If you are worried about checking if there is a value you could do the following to give you a -1 value if there is no integer at the begining of the string.

Match oMatch = Regex.Match("26 things", @"^\s*(\d+)");
int i = oMatch.Success ? int.Parse(oMatch.Groups[1].Value) : -1;

这篇关于是否有相当于到C的的atoi功能的.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆