-1

I have a string called source. This string contains tags, marked with number signs (#) on left and right side.

What is the most efficient way to get tag names from the source string. Source string:

let source = "Here is tag 1: ##TAG_1##, tag 2: ##TAG_2##."

Expected result:

["TAG_1", "TAG_2"]
Alexander
  • 59,041
  • 12
  • 98
  • 151
Ramis
  • 13,985
  • 7
  • 81
  • 100

3 Answers3

1

Not a very short solution, but here you go:

let tags = source.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " ,."))
    .filter { (str) -> Bool in
        return str.hasSuffix("##") && str.hasPrefix("##")
    }
    .map { (str) -> String in
        return str.stringByReplacingOccurrencesOfString("##", withString: "")
    }
Vishal
  • 2,030
  • 22
  • 27
1

Split the string at all occurences of ##:

let components = source.components(separatedBy: "##")
// Result: ["Here is tag 1: ", "TAG_1", ", tag 2: ", "TAG_2", "."]

Check that there's an odd number of components, otherwise there's an odd amount of ##s:

guard components.count % 2 == 1 else { fatalError("Unbalanced delimiters") }

Get every second element:

components.enumerated().filter{ $0.offset % 2 == 1 }.map{ $0.element }

In a single function:

import Foundation

func getTags(source: String, delimiter: String = "##") -> [String] {
    let components = source.components(separatedBy: delimiter)
    guard components.count % 2 == 1 else { fatalError("Unbalanced delimiters") }
    return components.enumerated().filter{ $0.offset % 2 == 1 }.map{ $0.element }
}

getTags(source: "Here is tag 1: ##TAG_1##, tag 2: ##TAG_2##.") // ["TAG_1", "TAG_2"]
Kametrixom
  • 14,673
  • 7
  • 45
  • 62
0

You can read this post and adapt the answer for your needs: Swift: Split a String into an array

If not you can also create your own method, remember a string is an array of characters, so you can use a loop to iterate through and check for a '#'

let strLength = source.characters.count;
var strEmpty = "";

for( var i=0; i < strLength; i++ )
{
   if( source[ i ] == '#' )
   {
     var j=(i+2);

     for( j; source[ (i+j) ] != '#'; j++ )
       strEmpty += source[ (i+j) ]; // concatenate the characters to another variable using the += operator

     i = j+2;
     // do what you need to with the tag
   }
}

I am more of a C++ programmer than a Swift programmer, so this is how I would approach it if I didn't want to use standard methods. There may be a better way of doing it, but I don't have any Swift knowledge. Keep in mind if this does not compile then you may have to adapt the code slightly as I do not have a development environment I can test this in before posting.

Community
  • 1
  • 1
MikeO
  • 391
  • 4
  • 17