Search code examples
arraysswiftstringalgorithmsubstring

Strings: How to combine first and last names in a long text string with other words?


Problem:

I have a given string = "Hello @User Name and hello again @Full Name and this works"

Desired output: = ["@User Name, @Full Name"]

Code I have in Swift:

let commentString = "Hello @User Name and hello again @Full Name and this works"
      let words = commentString.components(separatedBy: " ")
      let mentionQuery = "@"
      
      for word in words.filter({ $0.hasPrefix(mentionQuery) }) {
        print(word) = prints out each single name word "@User" and "@Full"
      }

Trying this:

if words.filter({ $0.hasPrefix(mentionQuery) }).isNotEmpty {
        print(words) ["Hello", "@User", "Name".. etc.]
      }

I'm stuck on how to get an array of strings with the full name = ["@User Name", "@Full Name"]

Would you know how?


Solution

  • First of all, .filter means that check each value in the array which condition you given and if true then take value - which not fit here.

    For the problem, it can divide into two task: Separate string into substring by " " ( which you have done); and combine 2 substring which starts with prefix "@"

    Code will be like this

    let commentString = "Hello @User Name and hello again @Full Name"
    let words = commentString.components(separatedBy: " ")
    let mentionQuery = "@"
    
    var result : [String] = []
    var i = 0
    while i < words.count {
        if words[i].hasPrefix(mentionQuery) {
            result.append(words[i] + " " + words[i + 1])
            i += 2
            continue
        }
        i += 1
    }
    

    The result

    print("result: ", result) // ["@User Name", "@Full Name"]