在 Swift 中替换字符串中的特定字符 [英] Replace specific characters in string in Swift

查看:184
本文介绍了在 Swift 中替换字符串中的特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用 Swift 3 替换字符串中的特定字符.

I am currently trying to replace specific characters in a string using Swift 3.

var str = "Hello"    
var replace = str.replacingOccurrences(of: "Hello", with: "_____")    
print(replace)

这将打印:_____ 但是当 str 更改并且包含不同数量的字符或多个单词时会出现我的问题,例如:

This will print: _____ but my problem occurs when str changes and consists of a different number of characters or several words such as:

var str = "Hello World"

现在我希望替换变量在 str 更改时自动更新.除空格"外的所有字符都应替换为 _,然后打印 _____ _____,它应该代表 Hello World.

Now I want the replace variable to update automatically when str is changed. All characters except 'Space' should be replaced with _ and later print _____ _____ which is supposed to represent Hello World.

如何实现?

推荐答案

如果要替换所有单词字符,可以使用 regularExpressions 输入到 options 参数使用您之前使用的相同函数,只需将特定的字符串输入更改为 \\w,它将匹配任何单词字符.

If you want to replace all word characters, you can use the regularExpressions input to the options parameter of the same function you were using before, just change the specific String input to \\w, which will match any word characters.

let str = "Hello World"
let replace = str.replacingOccurrences(of: "\\w", with: "_", options: .regularExpression) // "_____ _____"

请记住,\\w 也不会替换其他特殊字符,因此对于 "Hello World!" 的输入,它会生成 _____ _____!".如果要替换除空格之外的每个字符,请使用 \\S.

Bear in mind that the \\w won't replace other special characters either, so for an input of "Hello World!", it will produce "_____ _____!". If you want to replace every character but whitespaces, use \\S.

let replace = str.replacingOccurrences(of: "\\S", with: "_", options: .regularExpression)

这篇关于在 Swift 中替换字符串中的特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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