An example of a method for string interception and comparison in swift 3.0

  • 2020-05-30 21:10:45
  • OfStack


String manipulation 1 is inevitable in program development, and string interception/substitution is even more frequent. In swift3.0, subscript digits cannot be directly used for string resolution, but can only be used String.Index To do the location index, to achieve the interception function must first get String.Index;

Without further ado, let's take a look at the details.

The sample code

The following two pieces of code get the beginning can end, get the middle part of the parameters Range<Index> Can;

Gets the ending substring of two characters:

let sessionId = "this is a test"

 let index = sessionId.index(sessionId.endIndex, offsetBy: -2)
 let suffix = sessionId.substring(from: index)

The final result is: "st"

Gets the first two characters:

let sessionId = "this is a test"

 let index = sessionId.index(sessionId.startIndex, offsetBy: 2)
 let prefix = sessionId.substring(to: index)

The final result is: "th"

Example of a string comparison method:

 // String comparison 
  // Compare whether the characters are the same 
  let s1 = " good "
  let s2 = " good "
  if s1 == s2 {
   print("s1 == s2")
   print("s1 != s2")
  let s3:NSString = "ok"
  let s4:NSString = "ok!"
  if s3.isEqual(to: s4 as String) {
   print("s3 == s4")
   print("s3 != s4")
  // Compare the prefixes of strings , The suffix 
  let array = ["do.docx","good.docx","name.docx","data.json","good.json"]
  for d in array {
   if d.hasPrefix("good"){
    print(" The prefix for good:\(d)")
  for d in array {
   if d.hasSuffix(".json"){
    print(" The suffix for .json:\(d)")


Related articles: