'Remove empty space in modified text

I have a function that takes in text and checks for the @ symbol. The output is the same text, but any words following the @ symbol will be coloured, similar to that of a social media mention. The problem is that it adds an extra empty space to the front of the original text. How do I modify the output to remove the empty space it adds to the front of the new text?

func textWithHashtags(_ text: String, color: Color) -> Text {
        let words = text.split(separator: " ")
        var output: Text = Text("")

        for word in words {
            if word.hasPrefix("@") { // Pick out hash in words
                output = output + Text(" ") + Text(String(word))
                    .foregroundColor(color) // Add custom styling here
            } else {
                output = output + Text(" ") + Text(String(word))
            }
        }
        return output
    }

Just call the function in a view like

textWithHashtags("Hello @stackoverflow how is it going?", color: .red)


Solution 1:[1]

try something like this:

func textWithHashtags(_ text: String, color: Color) -> Text {
        let words = text.split(separator: " ")
        var output: Text = Text("")
        var firstWord = true // <-- here

        for word in words {
            let spacer = Text(firstWord ? "" : " ")  // <-- here
            if word.hasPrefix("@") { // Pick out hash in words
                output = output + spacer + Text(String(word))
                    .foregroundColor(color) // Add custom styling here
            } else {
                output = output + spacer + Text(String(word))
            }
            firstWord = false
        }
        return output
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1