Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first four letters from string in Swift 3?

Tags:

swift3

I am trying to do IFSCCode validation in swift, but the problem I'm facing is I am not able to fetch the first four letters in string.

IFSC Code example:

ABCD0200000

This is how an IFSC Code looks:

  1. First four characters in IFSC Code are always alphabets
  2. Fifth character is always a zero.
  3. And rest can be anything
  4. The length of IFSC Code should not be greater than or less than 11. It should 11 in length.

I have written code for ifs code validation in Objective C, but I am not that familiar in Swift so getting a problem in replicating the same in Swift.

The following is the code which I have written in Objective 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;   } } 

In 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 } 
like image 559
Rani Avatar asked Oct 18 '16 16:10

Rani


People also ask

How do I get the first character of a string in Swift?

In Swift, the first property is used to return the first character of a string.

How do I get the last two characters of a string in Swift 4?

In swift 4, the substring method has been deprecated and now we can use the suffix method of strings, which allow us to get the last few characters of any string.

How do I substring a string in Swift?

You can get a substring from a string by using subscripts or a number of other methods (for example, prefix , suffix , split ). You still need to use String. Index and not an Int index for the range, though. (See my other answer if you need help with that.)

How do I split a string in Swift 4?

To split a string to an array in Swift by a character, use the String. split(separator:) function. However, this requires that the separator is a singular character, not a string.


1 Answers

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]; 
like image 179
Tim Vermeulen Avatar answered Nov 13 '22 15:11

Tim Vermeulen