-3

I have the following String word = "12345"; I want to split each character and insert this into an int array

like this-

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

whats the fastest and easiest way to do this ?

2
  • Some search on the internet? There are thousand topics out there to split a string, convert a character to integer. Everythings out there. Commented Jun 24, 2016 at 11:46
  • Possible duplicate of convert char array to int array c# Commented Jun 24, 2016 at 11:48

3 Answers 3

4

Try using Linq:

  String word = "12345";

  int[] array = word
    .Select(c => c - '0') // fastest conversion
    .ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain what exactly is happening in that Select command?
@jpaugh78: c is char and after subtracting 0 Select returns integer difference between c and 0 which is 0 for 0, 1 for 1 ... 9 for 9
okay, I think that makes sense. I don't often deal with char, so it was a new concept for me.
3
String word = "12345";
int[] array = word.Select(x => int.Parse(x.ToString())).ToArray();

Comments

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();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.