-3

I have lines (string type) of numbers like "23 78 53 4 94 32 148 31". I need to put them into int array. Here's the lame code I wrote, but it doesn't work properly:

        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++;
            }
        }

It can be a one-, two- or three-digit number.

2
  • 2
    it doesn't work properly is not a helpful description of the problem. What do you expect to get? What did you get instead? Are you getting an error/exception? If so, what is and where is it happening? Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. Commented Oct 13, 2015 at 18:02
  • can you not just split by spaces and then Convert.ToInt32() on each one. You can either use a list or just allocate a new array of length, splitStringArray.Length Commented Oct 13, 2015 at 18:23

5 Answers 5

2

There are several ways to achieve what you want as the other answers point out. If you want a bit of safety checking then I'd use 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);
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

So if you have a string as such and all the numbers are separated by spaces

string foo = "12 34 567 120 12";

All you have to do is use string.Split(' ') to break this string into an array then convert those values to int values.

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

1 Comment

For safety, Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries) - still works if there are extra spaces.
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();

8 Comments

Downvoter, I think you'll post the reason...
Using a regular expression for something that .Split was made to do is a bit "overkill".
But it doesn't make it wrong. Just another alternative.. Also handles the case like @venerik posted, easily...
You're right, but I feel like when answering a question asked by a beginner, providing the most simple answer is the best option.
@JonathanCarroll Then people doesn' t need to upvote, but downvoting is .......
|
0

Use string.Split instead. You can split on each space and get an array. From there, parse each item to an int. You can actually do it all in one line with LINQ.

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

2 Comments

StringSplitOptions.RemoveEmptyEntries for additional safety.
@DonBoitnott good call.
0

Non-Linq answer

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.