0

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.

1
  • 3
    Providing sample input and output for us to work with would be nice. Commented Jul 29, 2010 at 12:53

7 Answers 7

3

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
            Else
                Key = LineValue.Trim("~")
            End If
        Next

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

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

    For Each Int as Integer in WolfVals
        Console.WriteLine(Int)
    Next

    Console.Read()
End Sub
Sign up to request clarification or add additional context in comments.

5 Comments

Interesting. I haven't used dictionaries before. Could you explain a little what is going on?
@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
Sorry, I was fixing your syntax highlighting. A little hack. Rollback if you wish.
@Anthony Ahh, I see. No prob. Wish SO would fix this nonsense.
@Josh, That makes a little more sense. What's the dim in front of input and dict?
2

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.

1 Comment

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.
1

As @Fadrian says:

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

foreach(var variable in originalstring.split(" ")){
 try{
  integers.Add(Convert.ToInt32(vaiable));
 }
 catch(){
  strings.Add(variable)
 }
}

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 ","

Comments

1

Pseudologic

  • 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))
    intList.Add(val);
   else
    textList.Add(item);
}

Comments

0

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

1 Comment

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.
0

You would have to have 2 different separators, example:

Wolf#100,45,4,5

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.

2 Comments

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.
0
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))
    {
        numbers.Add(value);
    }
    else
    {
        strings.Add(word);
    }
}

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.