4

如果我有一个像这样的字符串:

"26 things"

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

如果我使用 C,我只会使用 atoi 函数。但我似乎在 .NET 中找不到任何等效的东西。

从字符串开头获取整数的最简单方法是什么?

编辑:对不起,我模棱两可。在字符串中寻找空格字符的答案在许多情况下都有效(甚至可能是我的)。我希望在 .NET 中有一个 atoi 等效项。答案也应该适用于像“26things”这样的字符串。谢谢。

4

10 回答 10

14

这看起来很漂亮:

string str = "26 things";
int x = int.Parse(str.TakeWhile(ch => char.IsDigit(ch)).Aggregate("", (s, ch) => s + ch));

而且,对于真正想要 atoi 的人来说,无聊的解决方案:

[System.Runtime.InteropServices.DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int atoi(string str);
于 2009-07-08T14:50:22.467 回答
10

这应该可以工作(编辑为忽略字符串开头的空格)

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

如果您担心检查是否有值,如果字符串的开头没有整数,您可以执行以下操作给您一个 -1 值。

Match oMatch = Regex.Match("26 things", @"^\s*(\d+)");
int i = oMatch.Success ? int.Parse(oMatch.Groups[1].Value) : -1;
于 2009-07-08T14:48:41.813 回答
2

你可以使用Int32.Parse(stringVal.Substring(0, stringVal.indexOf(" "))

于 2009-07-08T14:48:20.300 回答
1

一种方法是

string sample = "26 things";
int x = int.Parse(sample.Substring(0, sample.IndexOf(" ")));
于 2009-07-08T14:49:11.017 回答
0

直接等效的是 int.Parse(string) 但我不完全确定它是否只取起始数字。

于 2009-07-08T14:46:15.530 回答
0

您可以在 Microsoft.VisualBasic.Conversion 命名空间中调用 Val。在您的场景中,它应该打印“26”。我不知道它在她的场景中是否 100% 兼容。这是规范的链接。

http://msdn.microsoft.com/en-us/library/k7beh1x9%28VS.71%29.aspx

于 2009-07-08T14:58:48.927 回答
0

如果你只想要整数

public String GetNumber (String input)
{
    String result = "";
    for (Int32 i = 0; i < input.Length; i++)
    {
        if (Char.IsNumber(input[i]))
        {
            result += input[i];
        }
        else break;
    }
    return result;
}
于 2015-04-23T12:39:13.427 回答
-1

试试这个:

int i = int.Parse("26 things".Split(new Char[] {' '})[0]);
于 2009-07-08T14:53:28.637 回答
-2

我可以这样想:

    public static string Filter(string input, string validChars) {
        int i;
        string result = "";
        for (i = 0; i < input.Length; i++) {
            if (validChars.IndexOf(input.Substring(i, 1)) >= 0) {
                result += input.Substring(i, 1);
            } else break;
        }
        return result ;
    }

并称之为:

Filter("26 things", "0123456789");
于 2009-07-08T14:47:50.847 回答
-2

你必须拆分字符串然后解析它:

var str = "26 things";
var count = int.Parse(str.Split(' ')[0]);
于 2009-07-08T14:49:23.107 回答