如何访问字符串中的数字?

时间:2012-01-29 00:48:35

标签: c#

string sequence = "12345";
int[] ziffern = new int[sequence.Count()];
for (int i = 0; i < sequence.Count(); i++)
{
    ziffern[i] =  Convert.ToInt32(sequence.ElementAt(i));
}

它不起作用。如何访问每个号码?

7 个答案:

答案 0 :(得分:3)

ElementAt将返回char

char转换为Int32时,您将获得该字符的 ASCII码

试试这个:

 string sequence = "12345";
 int[] ziffern = new int[sequence.Length];
 for (int i = 0; i < sequence.Length; i++)
 {
       ziffern[i] = Convert.ToInt32(sequence.Substring(i, 1));
 }

答案 1 :(得分:1)

你的意思是'每一个数字'?

string sequence = "12345";
int[] ziffern = new int[sequence.Length];
int idx = 0;
foreach (char c in sequence)
{
    if (int.TryParse(c.ToString(), out ziffern[idx])) idx++;
}
// idx contains # of valid digits found

http://msdn.microsoft.com/en-us/library/f02979c7.aspx

上查看Int32.TryParse(string, out int)

答案 2 :(得分:0)

您应该使用sequence.Length代替Count()扩展方法。 stringint[]都有此属性。

字符串实际上等同于char[],因此请使用它。

string sequence = "12345";
int[] ziffern = new int[sequence.Length];
for (int i = 0; i < sequence.Length; i++)
{
    ziffern[i] =  Convert.ToInt32(sequence[i]);
}

答案 3 :(得分:0)

您使用了GetNumericValue方法(Convert.ToInt32),该方法将表示数字的Char对象转换为数值类型。因此它是从该方法返回的ASCII代码。使用Parse和TryParse将字符串中的字符转换为Char对象。使用ToString将Char对象转换为String对象。  试试这个:

string sequence = "12345";
int[] ziffern = new int[sequence.Count()];
int bar;
for (int i = 0; i < sequence.Count(); i++)
{
    if (!int.TryParse(sequence.ElementAt(i).ToString(), out bar))
    {
    //Do something to correct the problem
    }
    else
    {
       ziffern[i] =  bar;
    }
}

答案 4 :(得分:0)

以下是将其转换为int[]的Linq解决方案:

    public int[] ExtractNumbers(string numbers)
    {
        return numbers
            .ToCharArray()
            .Select(x => Int32.Parse(x.ToString(CultureInfo.CurrentCulture)))
            .ToArray();
    }

答案 5 :(得分:0)

int[] numbers = new int[sequence.Length];

for(int i=0; i<sequence.Length; i++)
{
    numbers[i] = Convert.ToInt32(sequence[i].ToString());
}

答案 6 :(得分:0)

LINQ做得很好:

string sequence = "12345";
var ziffern = sequence.Select(c => (int)(c - '0')).ToArray();

或者你可以在那里使用Char.GetNumericValue(char c)方法,它也可以在字符串中处理像⅓这样的字符。