如何从字符串中去除特殊字符? [英] How to strip special characters out of string?

查看:95
本文介绍了如何从字符串中去除特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串中包含允许的字符集:

I have a set with the characters I allow in my string:

var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")

我想从一个字符串中去除任何其他字符,这样两个未格式化的数据就可以被认为是相等的,就像这样:

I want to strip any other characters from a string so two unformatted data can be considered equal, like this:

"American Samoa".lowercaseString == "american_samoa1".lowercaseString

这些转换后的字符串的小写版本将是 "americansamoa"

the lowercase version of these transformed strings would be "americansamoa"

推荐答案

让我们为此编写一个函数(在 swift 1.2 中).

Let's write a function for that (in swift 1.2).

func stripOutUnwantedCharactersFromText(text: String, set characterSet: Set<Character>) -> String {
    return String(filter(text) { set.contains($0) })
}

你可以这样称呼它:

let text = "American Samoa"
let chars = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
let strippedText = stripOutUnwantedCharactersFromText(text, set: chars)

纯粹的迅速.是的.

这篇关于如何从字符串中去除特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆