We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now


.NET C# stringtok equal to Java.

RSSIAdmin asked
Medium Priority
Last Modified: 2008-02-01
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?

Watch Question

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 += ",";  


Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
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.

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.