Question

In this question I mentioned that I'm working with strings that contain separate integer values, like so: "18 37 237". With that being said, further into my program I need to have individual access to these integers so that I can print them to a file. I'm guessing that the best way to do this would be to store them in an integer array with the size based off of how many ints are in the string.

These are my current goals for this question:

-Size integer array based on how many ints are in string

-Load array with ints (possibly using some sort of Regex method)

My question is, how would I code these goals? After solving the above goals I should be okay from there.

Update: To clear up confusion, I would like to point out that all of my strings contain other non-digits characters, most of them actually look like: "SampleText 12 23 34". I'm sorry for not clearing this up originally.

Was it helpful?

Solution

You might want to filter your sequence before using int.Parse:

var ints = str
           .Split()
           .Where(x => x.All(char.IsDigit))
           .Select(int.Parse)
           .ToArray();

char.IsDigit usually a good option but it allows all digits, not just only latin digits (from 0 to 9), if you want to allow only digits from 0 to 9 here is more preferable way:

var digits = new[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

var ints = str
          .Split()
          .Where(x => x.All(digits.Contains))
          .Select(int.Parse)
          .ToArray();

OTHER TIPS

You can use this code:

var ints = str.Split(' ').Select(x => int.Parse(x)).ToArray();

The way I would do this is by using String.Split and int.TryParse.

string[] strings = myString.Split( new string[]{ " " }, StringSplitOptions.RemoveEmptyEntries );
int[] ints = new int[ strings.Length ];
for( int i = 0; i < ints.Length; ++i )
{
    if( !int.TryParse( strings[i], out ints[i] )
    {
          // error
    }
}

If you really want an array, and your integers are always space delimited:

string[] seperateInts = testString.Split(' ');
int[] intArray = new int[seperateInts.Length];

for (int i = 0; i < seperateInts.Length; i++)
   int.TryParse(seperateInts[i], out intArray[i]);

A list is probably a better solution:

List<int> intList = new List<int>();
foreach (string s in testString.Split(' ');
{
   int parsedInt = 0;

   //Avoid bad ints
   if (int.TryParse(s, out parsedInt))
      intList.Add(parsedInt);
}

This regex will do what you expect

var subject = "18 37 237";
var regex = new Regex(@"\d+");
var myInts = regex.Matches(subject)
         .Cast<Match>()
         .Select(x=> int.Parse(x.Value))
         .ToArray();
string s  = "18 37 SomeText 237";
string[] resultOfSplit = s.Split(' ');
List<int> intList = List<int>();
for (var i=0; i<resultOfSplit.Length;i++)
    {
        int temp=0;
        if(Int.TryParse(resultOfSplit[i],out temp))
        {
            intList.Add(temp);
        }            
    }
// Below line to convert the list to an array
int[] intArray = intList.ToArray();

So, you would need to use .Split() and .TryParse()

Updated code to skip non-integer values in array

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top