0

I did some searching on here and couldn't find the answer I exactly needed. I have a struct that contains search parameters that I need to send to a Web Service, and one of the fields I am trying to fill is a List. The original code was written to fill this param. when it was of type string[], so it looked like this, with the variable names altered,

    searchParams.someParam= (new List<string>(txtboxInput.Text.Split(';'))).ToArray();

(The ; was delimiting the different options the user could enter)

So what I was thinking of filling the List with List.Add() 'while' there are tokens available. I searched if there was a StringTokenizer-like implementation in .NET. Most answers said to use string.Split, but do nothing to mention the other useful methods that Java's StringTokenizer had as well.

Thank you for any thoughtful replies.

darethas
  • 7,377
  • 3
  • 23
  • 32
  • also, I would rather avoid using .NET Regex in this particular case if possible, I realize that this is a possible solution. – darethas Jul 06 '12 at 17:07
  • what "useful" methods do you want? Also, that code splits into an array, moves it to a list and then back to an array. You can cut that out and just do the split. – scottheckel Jul 06 '12 at 17:10

2 Answers2

2

From the question, it looks like you just want:

List<string> list = txtboxInput.Text.Split(';').ToList();
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
1

I see a few things here that I think are what you're looking for (which is more of a question on how to work with Split(). We don't need a lot of the nextToken and hasMoreTokens methods Java's StringTokenizer has because they are built into the array returned by Split.

// From the question searchParams.someParam appears to be an array of strings, so you
// can simplify to this vs what is in your above question
searchParams.someParam = txtboxInput.Text.Split(';');

// Looping through and adding to a list of string
var myTokens = txtboxInput.Text.Split(';');
var myTokenList = new List<string>();
for(int index = 0; index < myTokens.length; index++) {
  myTokenList.Add(myTokens[index]);
}

// Total amount of tokens returned
var length = myTokens.length;

Also, RegEx doesn't make much sense here because you're just splitting a string. There's probably performance enhancements you can get depending on the size of the string but ultimately split is simpler. If you're not having performance issues then I wouldn't change from what you currently have.

scottheckel
  • 9,106
  • 1
  • 35
  • 47