Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

ios - How to get rid of a "non-breaking space" inside a Swift string?

I retrieved some strings from AddressBook.framework's ABRecordCopyValue method by casting the returned value of takeRetainedValue() as a String object.

let unmanagedFirstNameProperty = ABRecordCopyValue(person, kABPersonFirstNameProperty)
if unmanagedFirstNameProperty != nil {
    contactFirstName = unmanagedFirstNameProperty!.takeRetainedValue() as? String
}

let formattedName:String = contactFirstName.replaceOccurrences(of: " ", with: "")
print(formattedName)

I want to get rid of the spaces inside this String object by calling replaceOccurrences(of:with:) method, but that doesn't work (the spaces are still there after I call this method) and I was told by the Apple Framework Reference that this is usually because of the string encoding, containing "non-break spaces" which I've heard a lot about, but I have no idea how to make a "non-break space" into a normal space. Is this even possible? If so, what would be the best approach to make the characters inside a String compatible with the replaceOccurrences(of:with:) method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your code, where you have contactFirstName.replaceOccurrences(of: " ", with: "") is that space character typed in with the option key held down? If you type a space with the option key held down, you should get a non-breaking space.

Then you can replace it with a normal space, or an empty string if you wish.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...