I have an array ["abc", "94761178","790"]
I want to iterate each and check is a String or an Integer?
How to check it ?
How to convert "123" to integer 123
You can think of a string as plain text. A string represents alphanumeric data. This means that a string can contain many different characters, but they are all considered as if they were text, even if the characters are numbers. A string can also contain spaces.
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.
Here is a small Swift version using String extension :
Swift 3/Swift 4 :
extension String { var isNumber: Bool { return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil } }
Swift 2 :
extension String { var isNumber : Bool { get{ return !self.isEmpty && self.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) == nil } } }
Edit Swift 2.2:
In swift 2.2 use Int(yourArray[1])
var yourArray = ["abc", "94761178","790"] var num = Int(yourArray[1]) if num != nil { println("Valid Integer") } else { println("Not Valid Integer") }
It will show you that string is valid integer and num
contains valid Int
.You can do your calculation with num
.
From docs:
If the string represents an integer that fits into an Int, returns the corresponding integer.This accepts strings that match the regular expression "[-+]?[0-9]+" only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With