Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading