简体   繁体   中英

how can i add extra spaces before any special character

how to add extra spaces before any Special character in string,in Swift, for example if i have string

var str = "#StackOverFlow@is$awesome"

 " #StackOverFlow  @is  $awesome"   // i have to achieve this...add empty spaces before every # 

how can we solve and achieve this in Swift

You can use a regular expression to match any special character "[^\\w]" which means any non word character and replace by the same match "$0" preceded by white spaces. If you would like to exclude whitespaces from being replaced you can use "[^\\w|\\s]" :

let str =  "#StackOverFlow#is#awesome"
let result = str.replacingOccurrences(of: "[^\\w]",
                          with: "   $0",
                          options: .regularExpression)


print(result)  // "   #StackOverFlow   #is   #awesome\n"

let str2 =  "•StackOverFlow•is•awesome"
let result2 = str2.replacingOccurrences(of: "[^\\w]",
                          with: "   $0",
                          options: .regularExpression)


print(result2)  // "   •StackOverFlow   •is   •awesome\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM