Skip to content

Instantly share code, notes, and snippets.

@rurumimic
Created September 14, 2018 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rurumimic/66a9f3f763b63a208c9ce0fb970defd5 to your computer and use it in GitHub Desktop.
Save rurumimic/66a9f3f763b63a208c9ce0fb970defd5 to your computer and use it in GitHub Desktop.
String 만지기
import Foundation
let s = "Hello, World!"
print(s)
// string -> string array
var a = s.map { String($0) }
print(a)
// string array -> string
//let b = a.reduce("") { $0 + $1 }
let b = a.reduce("", +)
print(b)
extension String {
func contains(s: String) -> Bool
{
return self.range(of: s) != nil ? true : false
}
func isMatch(pattern: String, options: NSRegularExpression.Options) -> Bool {
let range = NSRange(location: 0, length: self.count)
let regex = try! NSRegularExpression(pattern: pattern, options: options)
let result = regex.matches(in: self, options: [], range: range)
return result.count > 0
}
func getMatchesString(pattern: String, options: NSRegularExpression.Options) -> [String] {
let range = NSRange(location: 0, length: self.count)
let regex = try! NSRegularExpression(pattern: pattern, options: options)
let result = regex.matches(in: self, options: [], range: range)
return result.map { String(self[Range($0.range, in: self)!]) }
}
func getMatches(pattern: String, options: NSRegularExpression.Options) -> [NSTextCheckingResult] {
let range = NSRange(location: 0, length: self.count)
let regex = try! NSRegularExpression(pattern: pattern, options: options)
let result = regex.matches(in: self, options: [], range: range)
return result
}
subscript (at: Int) -> String
{
get {
guard let s = index(startIndex, offsetBy: at, limitedBy: endIndex) else { return "" }
guard let e = index(startIndex, offsetBy: at+1, limitedBy: endIndex) else { return "" }
return String(self[s..<e])
}
}
subscript (begin: Int, end: Int) -> String
{
get {
guard let s = index(startIndex, offsetBy: begin, limitedBy: endIndex) else { return "" }
guard let e = index(startIndex, offsetBy: end, limitedBy: endIndex) else { return String(self[s..<endIndex]) }
return String(self[s..<e])
}
}
}
print(s.contains(s: "llo"))
print(s[0, 5])
print(s[100, 4])
print(s[4, 100])
print(s[4, 5])
print(s[4])
print(s.isMatch(pattern: "Hello", options: []))
print(s.getMatches(pattern: "[a-z]+", options: [])[1].range.location)
print(s.getMatches(pattern: "[a-z]+", options: [])[1].range.length)
print(s.getMatchesString(pattern: "[a-z]+", options: []))
print(s.replacingOccurrences(of: "World", with: "yap"))
print(s)
@rurumimic
Copy link
Author

Hello, World!
["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d", "!"]
Hello, World!
true
Hello

o, World!
o
o
true
8
4
["ello", "orld"]
Hello, yap!
Hello, World!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment