• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 254
  • Last Modified:

.NET C# stringtok equal to Java.

Hi Expert:

I am creating a string with a list of words and each word is to be separated by a comma (name1,house,doe,truck,work etc...).

I don't know actually how many words will be in the list until the end of the function.

I worked something up ( stringvar+= ", ") to put a comma in between each word.

But in the case when function ends with only one word in the list , I get a comma after that one word which is not what I want!

I know I can strip the comma off the one word string at the end of function but how do the experts do this whole thing?

2 Solutions
I usually add the comma if its not the last item in the loop like:

string strtemp = "";
for (int i = 0;i<10;i++)
  strtemp += i.ToString();
  if (i < 10)
     strtemp += ",";  

For a start I would use the System.Text.Stringbuilder to build up your string - I think I'm right when I say that it is a LOT more memory efficient if you are concatenating a lot of strings together. The System.String is immutable; i.e. methods that appear to modify it just return a new instance of it. The StringBuilder, however, is mutable.

Essentialy stringvar += "newword," creates an entirely new string in memory each time, it doesn't just add the new part to the end of the existing one - baaaaaad. So this uses lots and lots of strings in memory (I've forgotten how to count past 5):
  string stringvar = "a";
  string word2 = "b";
  stringvar += ",";
  stringvar += word2;

Instead, we can do:
   StringBuilder strbString = new StringBuilder;
   <pseudocode>foreach string word in wordsource.words</p>
      strbString.AppendFormat("{0},", word);
   // now remove the last comma from the stringbuilder
   // and then get the string
   string mystringlist = strbString.ToString();

Where is your word list coming from by the way? Is it some kind of object array so you know the length? If so, then yes, you can miss off the last comma.


Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now