Skip to content

Instantly share code, notes, and snippets.

@MTattin
Created August 16, 2017 10:20
Show Gist options
  • Save MTattin/19bd0836ef81870a849bd68bd4850939 to your computer and use it in GitHub Desktop.
Save MTattin/19bd0836ef81870a849bd68bd4850939 to your computer and use it in GitHub Desktop.
swift4の文字列操作(Substring)メモ ref: http://qiita.com/MTattin/items/f97d1a51efd8eac109cf
///
/// 対象文字列
///
let str: String = "1234567890"
///
/// 先頭1文字 - 1
///
print("先頭1文字: \(String(str.prefix(1)))")
///
/// 先頭1文字以外 - 234567890
///
print("先頭1文字以外: \(String(str[str.index(after: str.startIndex)..<str.endIndex]))")
print("先頭1文字以外: \(String(str.suffix(str.characters.count - 1)))")
///
/// 末尾1文字 - 0
///
print("末尾1文字: \(String(str.suffix(1)))")
///
/// 末尾1文字以外 - 123456789
///
print("末尾1文字以外: \(String(str[str.startIndex..<str.index(before: str.endIndex)]))")
print("末尾1文字以外: \(String(str.prefix(str.characters.count - 1)))")
///
/// 先頭から?文字 - 12345
///
print("先頭から?文字: \(String(str.prefix(5)))")
///
/// 末尾から?文字 - 67890
///
print("末尾から?文字: \(String(str.suffix(5)))")
///
/// 先頭?文字以外 - 67890
///
print("先頭?文字以外: \(String(str[str.index(of: "6")!..<str.endIndex]))")
print("先頭?文字以外: \(String(str.suffix(str.characters.count - 5)))")
///
/// 末尾?文字以外 - 12345
///
print("末尾?文字以外: \(String(str[str.startIndex..<str.index(of: "6")!]))")
print("末尾?文字以外: \(String(str.prefix(str.characters.count - 5)))")
///
/// ?から?文字 - 34567
///
print("?から?文字: \(String(str[str.index(of: "3")!..<str.index(of: "8")!]))")
print("?から?文字: \(String(str[str.index(of: "3")!...str.index(of: "7")!]))")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment