How to remove newlines from a string Swift

2 Answers

0 votes
import Foundation

func removeNewlines(_ s: String) -> String {
    s.replacingOccurrences(of: "\n", with: "")
     .replacingOccurrences(of: "\r", with: "")
}

let s = "c# \n  c c++  \n java python\ngo\n";
let result = removeNewlines(s)

print(result)




/*
run:

c#   c c++   java pythongo

*/

 



answered Feb 22 by avibootz
0 votes
import Foundation

func removeNewlines(_ s: String) -> String {
    let collapsed = s.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
    
    return collapsed.trimmingCharacters(in: .whitespacesAndNewlines)
}

let s = "c# \n  c c++  \n java python\ngo\n";
let result = removeNewlines(s)

print(result)



/*
run:

c# c c++ java python go

*/

 



answered Feb 22 by avibootz
...