0

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.

6 Answers 6

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

You can use this code:

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

7 Comments

if there is one invalid character, for ex. a letter it will throw an exception.
@Selman22: So are you saying if there are other characters besides integers? @FlatEric: is ints acting as an array?
@Ericafterdark I'am saying if there is non-digit characters in your strings, then int.Parse method will throw a FormatException
@Eric after dark, yes ints is an integer array here (just other syntax)
@Ericafterdark you keep on adding comments that say it needs to works with non-integers in the string. Update the question to be more specific. In fact, your question as it stands makes it seem like the string is well formed and only contains integers. "I'm working with strings that contain separate integer values, like so: "18 37 237"."
|
0

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

3 Comments

Do I need a temporary out variable?
Your code looks fine, I've never seen that overload of Split() used before though!
@LordTakkera I guess, it should really be a new char[]{ ' ' } but you want to remove the empty entries, so you shouldn't just use Split(' ')
0

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

Comments

0

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

1 Comment

Does this even work with strings that contain non-digit characters, like this: "Hello 12 23 34"?
0
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

7 Comments

The only problem with this is that my strings have other non-digit characters, like so: "Hello 23 34 23".
For them, do you want 0 (or any other default number say -1) to be added instead or should be skipped?
They should be skipped
Do you NEED an array, though? Wouldn't a list work for your case?
Come to think of it, that would probably be okay, I just thought of an array first for some reason. So that means I don't need to convert it then, correct?
|

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.