Split tag string


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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. }

URL: http://www.planetjonny.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.