I've got a string containing both ints and a string. How do I split it into two arrays, one for ints and one for the string? I also need to maintain the order because I'm writing a file parsing system that depends on reading in and correctly splitting these strings.

EDIT: Here's a sample input, and what I would like as output:

~Wolf 100 45 4 5

Wolf as a string in an array and the ints in their own separate array.

EDIT: A little more info:

I'm getting five variables from the user and writing them to a file. Then, I'm reading them back in again. I need to be able to identify the numbers by the name. Now that I think about it, actually, I'm not sure splitting the string is the best way to go. Is there a way to put both ints and strings in a single array? That way I can find the name, and know that the next four ints after it belong to it.


It depends on how the data is stored in that string. If there's a separator between the numbers, use String.Split()

Hamid Nazari
I can easily put a seperator between the numbers, but how do I get two arrays out of String.Split? As far as I know, it outputs one array.
Elliot Bonneville
+1  A: 


  • First split the string into an array
  • Create a List<int> and List<string>
  • Iterate thru the array and use Int.TryParse and if the return is true, insert into the List<int>, otherwise List<string>

--- Edited with example -----

var list = line.Split(',', StringSplitOptions.RemoveEmptyEntries);
var intList = new List<int>();
var textList = new List<string>();
int val = 0;
foreach(var item in list)
   if(Int.TryParse(item, out val))
Fadrian Sudaman
I haven't worked with lists yet. What's the correct syntax?
Elliot Bonneville
@Fadrian Okay, thanks. +1
Elliot Bonneville
+1  A: 

As @Fadrian says:

List<int> integers = new List<int>();
List<string> strings= new List<string>();

foreach(var variable in originalstring.split(" ")){

But from what I can read I would do something else. I would create an XML or database table or somethin.

IF it really has to be in plain text file, use a different delimiter for your name, and numbers: eg

name | number1 ,number2,number...

then split once on "|" and first one is name, second one numbers. Then split the second one on ","


You would have to have 2 different separators, example:


Then you could perform:

string[] splitTheFirst = String.Split('#');
string[] splitTheSecond = splitTheFirst[0].Split(',');
int[] splitTheThird = splitTheFirst[1].Split(',');

Then you would have an array of strings with the strings from the first split, and an array of ints from the second array from the first split.

Sorry, you'd have to have them all as string[], as that's what String.Split returns, and then you'd have to do Convert.ToInt32 on each string in splitTheThird - d'oh!
Reading the extra information you've added to your quesion, this won't work for you.
Yeah, I wasn't clear enough to begin with.
Elliot Bonneville
+2  A: 

I need to be able to identify the numbers by the name.

I'll not repeat the string.split answers, but perhaps you shouldn't use arrays in both cases but could use an object to represent the user? e.g.

public class User
  public string UserName{get;set;}
  public List<int> Parameters= new List<int>();

You could then put the user into an array,list, dictionary etc to look up the user and then retrieve the parameters that the user has input.

Hah, thanks. Glad someone's paying attention to the OP. (me)
Elliot Bonneville
+1 was going to suggest more or less this.
Binary Worrier
The other advantage of this approach is that you could create the class from their input. If you make the class serializable (e.g. [XmlSerializable]) then you could let the framework do the reading/writing for you.
+3  A: 

Use a Dictionary(Of TKey, TValue) with a String as the key, and an Integer() array as the value. This will give you the lookup functionality you are looking for...

Sub Main()
    Dim Input As String = "~Wolf 100 45 4 5" & Environment.NewLine & _
                          "~Racoon 500 41 9 7"

    Dim Dict As New Dictionary(Of String, Integer())

    For Each Line As String In Input.Split(Environment.NewLine)
        Dim Key As String
        Dim Values As Integer() = New Integer() {}

        For Each LineValue As String In Line.Split(" "c)
            Dim TryInt As Integer

            If Integer.TryParse(LineValue, TryInt) Then
                ReDim Preserve Values(Values.Length)
                Values(Values.Length - 1) = TryInt
                Key = LineValue.Trim("~")
            End If

        If Not String.IsNullOrEmpty(Key) Then
            Dict.Add(Key, Values)
        End If

    ' How to use                             \\'
    Dim WolfVals As Integer() = Dict.Item("Wolf")

    For Each Int as Integer in WolfVals

End Sub
Josh Stodola
Nice syntax highlighting, StackOverflow...
Josh Stodola
Interesting. I haven't used dictionaries before. Could you explain a little what is going on?
Elliot Bonneville
@Elliot It is fairly self explanatory. See the input? It reads it line by line, splits each line by a space, builds the integer array, stores the key, then populates the dictionary
Josh Stodola
Sorry, I was fixing your syntax highlighting. A little hack. Rollback if you wish.
Anthony Pegram
@Anthony Ahh, I see. No prob. Wish SO would fix this nonsense.
Josh Stodola
@Josh, That makes a little more sense. What's the `dim` in front of `input` and `dict`?
Elliot Bonneville
@Elliot This is VB.NET. You can convert to C# here:
Josh Stodola
string input = "~Wolf 100 45 4 5";
IEnumerable<string> words = input.Split(' ')
                            .Where(a => a != null && a.Trim() != string.Empty);

List<int> numbers = new List<int>();
List<string> strings = new List<string>();
int value;

foreach (string word in words)
    if (int.TryParse(word, out value))