Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check is a string or number

Tags:

swift

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

like image 897
user3675188 Avatar asked Oct 24 '14 09:10

user3675188


People also ask

Is a string or number?

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.

How do I verify a string?

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.

How do you check if a string is a number in C++?

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.


2 Answers

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             }         }    } 
like image 177
CryingHippo Avatar answered Oct 03 '22 11:10

CryingHippo


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.

like image 35
codester Avatar answered Oct 03 '22 10:10

codester