字符串由字符分隔并插入到int数组中

时间:2016-06-24 11:31:29

标签: c# split

我有以下String word = "12345";我想拆分每个字符并将其插入一个int数组

像这样 -

int[] array = { 1, 2, 3, 4, 5};

最简单,最简单的方法是什么?

3 个答案:

答案 0 :(得分:4)

尝试使用 Linq

  String word = "12345";

  int[] array = word
    .Select(c => c - '0') // fastest conversion
    .ToArray();

答案 1 :(得分:3)

String word = "12345";
int[] array = word.Select(x => int.Parse(x.ToString())).ToArray();

答案 2 :(得分:0)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;

public static class Extensions
{
    /// <summary>
    /// Creates a int array from a String.
    /// </summary>
    /// <param name="source">The source.</param>
    /// <returns>an Int Array</returns>
    public static IObservable<IEnumerable<int>> StringToIntArray(this string source)
    {
        return Observable.Create<IEnumerable<int>>(sub =>
        {
            var sourceAsStringArray = source.ToCharArray().Select(x => x.ToString());
            var l = new List<int>();
            foreach (var s in sourceAsStringArray)
            {
                int output = -1;
                if (int.TryParse(s, out output))
                {
                    l.Add(output);
                }
            }

            sub.OnNext(l);
            sub.OnCompleted();
            return Disposable.Empty;
        });
    }

}

private async void Test()
    {
       var a = await "12345".StringToIntArray();
       var b = await "1a234b5".StringToIntArray();
       var invalid = await "IAmNotANumber".StringToIntArray();
    }