2016-10-18 38 views
12

我想在swift中做IFSCCode驗證,但是我面臨的問題是我無法獲取字符串中的前四個字母。如何從Swift 3中的字符串獲取前四個字母?

IFSC代碼示例:

ABCD0200000

這是一個IFSC代碼的外觀:

  1. 在IFSC代碼的前四個字符總是字母
  2. 第五個字符是總是一個零。
  3. 其餘部分可以是任何東西
  4. IFSC代碼的長度不應大於或小於11,長度應爲11。

我已經編寫了Objectives 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; 
    } 
} 

在夫特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 
} 
+0

你究竟需要什麼幫助? – rmaddy

回答

8

這是使用正則表達式的簡單驗證。該圖案表示:

  • ^必須是字符串的開頭
  • [A-Za-z]{4} =四個字符AZ或az
  • 0一個零
  • .{6} 6任意字符
  • $必須的端部字符串

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

PS:要回答你的問題,你在斯威夫特3的前4個字符與

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

感謝您的解決方案@vadian – Rani

+0

謝謝它的工作很好。 – Raja

49

最簡單的方式得到一個字符串的前綴是

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

// Swift 4 
string.prefix(4) 
+1

完美!謝謝 – Vinestro

0

你可以使用prefix()方法實現它,該方法將返回一個Swift Substring
然後,您可以使用String(_:)將其轉換爲字符串初始化。

例子:前4個字母

let myString = "123456789" 
let myStringPrefix = String(myString.prefix(4)) // result is "1234" 


如果字符串少於4個字母,最低將返回

相關問題