如何在 Swift 3中获得字符串的前四个字母?

我正在尝试快速地进行 IFSCCode 验证,但是我面临的问题是我无法获取字符串中的前四个字母。

综合家庭服务中心代码示例:

ABCD0200000

IFSC 守则如下:

  1. IFSC 代码的前四个字符总是字母
  2. 第五个字符总是零。
  3. 休息可以是任何东西
  4. IFSC 编码的长度不应大于或小于11。它的长度应为11。

我已经在 Objective C 中编写了 ifs 代码验证的代码,但是我对 Swift 并不熟悉,所以在 Swift 中复制同样的代码时遇到了问题。

以下是我在目标 C 中编写的代码:

- (BOOL)validateIFSCCode:(NSString*)ifsccode {
if (ifsccode.length < 4) {
return FALSE;
}
for (int i = 0; i < 4; i++) {
if (![[NSCharacterSet letterCharacterSet]
characterIsMember:[ifsccode characterAtIndex:i]]) {
return FALSE;
}
}
if (ifsccode.length < 10) {
return FALSE;
}
if ([ifsccode characterAtIndex:4] != '0') {
return FALSE;
} else {
return TRUE;
}
}

在 Swift 3里

func validateIfscCode(_ ifscCode : String) -> Bool{
if(ifscCode.characters.count < 4){
return false;
}


for( _ in 0 ..< 4){
let charEntered = (ifscCode as NSString).character(at: i)
}
if(ifscCode.characters.count < 10){
return false;
}


let idx = ifscCode[ifscCode.index(ifscCode.startIndex, offsetBy: 4)]


print("idx:%d",idx)
if (idx == "0"){
}
return true
}
73430 次浏览

This is a simple validation using regular expression. The pattern represents:

  • ^ must be the beginning of the string
  • [A-Za-z]{4} = four characters A-Z or a-z
  • 0one zero
  • .{6} six arbitrary characters
  • $ must be the end of the string

Updated to Swift 4

func validateIFSC(code : String) -> Bool {
let regex = try! NSRegularExpression(pattern: "^[A-Za-z]{4}0.{6}$")
return regex.numberOfMatches(in: code, range: NSRange(code.startIndex..., in: code)) == 1
}

PS: To answer your question, you get the first 4 characters in Swift 3 with

let first4 = code.substring(to:code.index(code.startIndex, offsetBy: 4))

and in Swift 4 simply

let first4 = String(code.prefix(4))

The easiest way to get a string's prefix is with

// Swift 3
String(string.characters.prefix(4))


// Swift 4 and up
string.prefix(4)


// Objective-C
NSString *firstFour = [string substringToIndex:4];

Swift 5

string.prefix(4)  // Replace 4 with number of letters you want to get from the string

This is working on Xcode 10.2.

Extention to get all substring

extension String {
func first(char:Int) -> String {
return String(self.prefix(char))
}


func last(char:Int) -> String
{
return String(self.suffix(char))
}


func excludingFirst(char:Int) -> String {
return String(self.suffix(self.count - char))
}


func excludingLast(char:Int) -> String
{
return String(self.prefix(self.count - char))
}
}