Posted By

mcbutterbuns on 10/29/10


Tagged

tags split


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


Split tag string


 / Published in: C#
 

URL: http://www.planetjonny.com

This code should split a tag string provided in a format similar to YouTube or Flickr.

Input string: tag1 tag2 "tag3 tag4"

Output as a list: tag1 tag2 tag3 tag4

I'm not entirely positive this works. I just wrote it for a coworker but hopefully it will provide someone with a starting point if it doesn't work.

  1. public List<string> splitTags(string tags)
  2. {
  3. StringBuilder b = new StringBuilder();
  4. List<string> tagList = new List<string>();
  5. bool inQuoteState = false;
  6.  
  7. foreach (char character in tags.ToCharArray())
  8. {
  9. switch (character)
  10. {
  11. case '"':
  12. if (inQuoteState){
  13. tagList.Add(b.ToString());
  14. b = new StringBuilder();
  15. }
  16.  
  17. inQuoteState = !inQuoteState;
  18. break;
  19. case ' ':
  20. if (!inQuoteState)
  21. {
  22. if (b.Length > 0) //don't add empty tags
  23. tagList.Add(b.ToString());
  24.  
  25. b = new StringBuilder();
  26. }
  27. else
  28. b.Append(character);
  29. break;
  30. default:
  31. b.Append(character);
  32. break;
  33. }
  34. }
  35.  
  36. return tagList;
  37. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: lelis718 on February 4, 2011

The code doesn´t save the last tag.

put a

if(b.Length > 0) tagList.Add(b.ToString());

before the return;

You need to login to post a comment.