Search code examples
iosswiftalgorithmswift-string

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


Solution

  • 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"