如何从字符串中删除或替换所有标点符号? [英] How can I remove or replace all punctuation characters from a String?

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

问题描述

我有一个由单词组成的字符串,其中有些包含标点符号,我想删除这些单词,但是我一直无法弄清楚该怎么做.

I have a string composed of words, some of which contain punctuation, which I would like to remove, but I have been unable to figure out how to do this.

例如,如果我有类似的东西

For example if I have something like

var words = "Hello, this : is .. a  string?"

我希望能够使用

"[Hello, this, is, a, string]"

我最初的想法是使用words.stringByTrimmingCharactersInSet()之类的东西来删除我不想要的任何字符,但这只会去除字符的末端.

My original thought was to use something like words.stringByTrimmingCharactersInSet() to remove any characters I didn't want but that would only take characters off the ends.

我想也许我可以用一些类似的东西遍历字符串

I thought maybe I could iterate through the string with something in the vein of

for letter in words {
    if NSCharacterSet.punctuationCharacterSet.characterIsMember(letter){
        //remove that character from the string
    }
}

但是我不确定如何从字符串中删除字符.我确定if语句的设置方式也存在一些问题,但这显示了我的思考过程.

but I'm unsure how to remove the character from the string. I'm sure there are some problems with the way that if statement is set up, as well, but it shows my thought process.

推荐答案

Xcode 10.2•Swift 5或更高版本

extension StringProtocol {
    var words: [SubSequence] {
        return split{ !$0.isLetter }
    }
}


let sentence = "Hello, this : is .. a  string?"
let words = sentence.words  // ["Hello", "this", "is", "a", "string"]

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

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