SoFunction
Updated on 2025-04-11

Example of method to implement string interception and comparison in swift 3.0

Preface

String processing has always been inevitable in program development, and string interception/replacement operations are even more frequent. Swift3.0 cannot directly use subscript numbers for string resolution, onlyTo do position indexing, if you want to implement the intercept function, you must first obtain it.;

I won’t say much below, let’s take a look at the detailed introduction together.

Example code

The following two codes can get the beginning and end, and use the middle part parameters to getRange<Index>Just do it;

Get the ending two substrings:

let sessionId = "this is a test"


 let index = (, offsetBy: -2)
 
 let suffix = (from: index)

The final result is: "st"

Get two starting characters:

let sessionId = "this is a test"


 let index = (, offsetBy: 2)
 
 let prefix = (to: index)

The final result is: "th"

Example of string comparison method:

 //String comparison  //Compare whether the characters are the same  let s1 = "OK"
  let s2 = "OK"
  if s1 == s2 {
   print("s1 == s2")
  }else{
   print("s1 != s2")
  }
  
  let s3:NSString = "ok"
  let s4:NSString = "ok!"
  if (to: s4 as String) {
   print("s3 == s4")
  }else{
   print("s3 != s4")
  }
  
  //Compare the prefix and suffix of the string  let array = ["","","","",""]
  for d in array {
   if ("good"){
    print("The prefix isgood:\(d)")
   }
  }
  
  for d in array {
   if (".json"){
    print("The suffix is.json:\(d)")
   }
  }

Summarize

The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.