Home > Blockchain >  Retrieve from an API and remove Strings after white space
Retrieve from an API and remove Strings after white space

Time:08-06

Summarize the problem
I've build an App and retrieving elements from an external API (Breaking Bad) and I was getting struggles of a simple String formatting. My scope is to remove after the white space the other strings.

What I've tried
I tried to follow guides that tries to recognize my whitespace element from a string called : "actor.name" but I don't know how to say "now that you recognized the white space, remove me all the string after this one". I used this parameter actor.name..filter({!$0.isWhitespace} but it only recognize the white space and remove it in some way. Then I tried this : actor.components(separatedBy: .whitespaces).joined(separator: " ") but I think that I'm out of track.

Show some code
It's not about showing a lot of my code.. I've just got this situation (I intentionally deleted useless piece of code) :

Text(actor.name.components(separatedBy: .whitespaces).joined(separator: " "))
            .bold()
            .foregroundColor(.white)
            .multilineTextAlignment(.center)
            .padding(.horizontal)
    }

CodePudding user response:

try this example code to ...remove Strings after white space. The code first removes any leading, trailing whitespaces, then split the string into components, and pick the first component [0].

let txt = actor.name.trimmingCharacters(in: .whitespaces).components(separatedBy: .whitespaces)
Text(txt.count > 0 ? txt[0] : "")
        .bold()
        .foregroundColor(.red)
        .multilineTextAlignment(.center)
        .padding(.horizontal)
  • Related