将数字从字符串放入int数组

时间:2015-10-13 17:57:54

标签: c#

我有数字的行(字符串类型),例如“ 23 78 53 4 94 32 148 31 ”。我需要将它们放入int数组中。这是我写的蹩脚代码,但它无法正常工作:

        int currentArrayValue=0;
        int currentChar=0;

        for (int i = 0; i < text1.Length; i++)
        {
            if (text1[i] != ' ')
            {
                currentChar++;
                continue;
            }

            else
            {
                for (int k = 1; k <=currentChar; k++)
                {
                    if (k == 1) Array[currentArrayValue] = text1[i - currentChar];
                    else if (k == 2) Array[currentArrayValue] = text1[i - currentChar] * 10;
                    else if (k == 3) Array[currentArrayValue] = text1[i - currentChar] * 100;
                }
                currentArrayValue++;
            }
        }

它可以是一位,两位或三位数字。

5 个答案:

答案 0 :(得分:2)

正如其他答案所指出的,有几种方法可以达到你想要的效果。如果你想进行一些安全检查,那么我会使用TryParse

using System;
using System.Collections.Generic;               
using System.Linq;

public class Program
{
    public static void Main()
    {
        var test = "1 2 3 x";
        var values = test.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
        var results = new List<int>();
        foreach(var value in values)
        {
            int x;
            if(Int32.TryParse(value, out x))
            {
               results.Add(x);
            }
            else
            { 
                Console.WriteLine("{0} is not an integer", value);
            }
        }
    }
}

答案 1 :(得分:1)

因此,如果您有一个字符串,并且所有数字都以空格分隔

string foo = "12 34 567 120 12";

您所要做的就是使用string.Split(' ')将此字符串分解为数组,然后将这些值转换为int值。

int[] intArray = foo.Split(' ').Select(x => Convert.ToInt32(x)).ToArray();

答案 2 :(得分:0)

请改用string.Split。您可以拆分每个空间并获得一个数组。从那里,将每个项解析为int。实际上,您可以使用LINQ在一行中完成所有操作。

int[] myInts = text1.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => int.Parse(s)).ToArray(); 

答案 3 :(得分:0)

string input = "23 78 53 4 94 32 148 31";
var arr = Regex.Matches(input, @"\d+").Cast<Match>().Select(m => int.Parse(m.Value)).ToArray();

答案 4 :(得分:0)

非Linq回答

const string inputVal = "23 78 53 4 94 32 148 31";
string[] splitInput = inputVal.Split(' ');
int[] inputIntArray = new int[splitInput.Length];
int counter = 0;
foreach (string split in splitInput){
    inputIntArray[counter++] = int.Parse(split);
}