如果我有一个像这样的字符串:
"26 things"
Run Code Online (Sandbox Code Playgroud)
我想将它转换为26.我只想在字符串开头的整数.
如果我使用C,我只使用atoi功能.但我似乎无法在.NET中找到任何相同的东西.
从字符串开头获取整数的最简单方法是什么?
编辑:对不起,我很暧昧.在字符串中查找空格字符的答案将在许多情况下起作用(甚至可能是我的).我希望在.NET中使用atoi.答案也应该使用像"26things"这样的字符串.谢谢.
Tim*_*mbo 14
这看起来太漂亮了:
string str = "26 things";
int x = int.Parse(str.TakeWhile(ch => char.IsDigit(ch)).Aggregate("", (s, ch) => s + ch));
Run Code Online (Sandbox Code Playgroud)
对于任何真正想要atoi的人来说,这是一个无聊的解决方案:
[System.Runtime.InteropServices.DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int atoi(string str);
Run Code Online (Sandbox Code Playgroud)
ste*_*ell 10
这应该工作(编辑忽略字符串开头的空格)
int i = int.Parse(Regex.Match("26 things", @"^\s*(\d+)").Groups[1].Value);
Run Code Online (Sandbox Code Playgroud)
如果您担心检查是否有值,如果在字符串的开头没有整数,则可以执行以下操作以给出-1值.
Match oMatch = Regex.Match("26 things", @"^\s*(\d+)");
int i = oMatch.Success ? int.Parse(oMatch.Groups[1].Value) : -1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3227 次 |
| 最近记录: |