Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how to check whether a string contains an integer?

I just want to know, whether a String variable contains a parsable positive integer value. I do NOT want to parse the value right now.

Currently I am doing:

int parsedId; if (     (String.IsNullOrEmpty(myStringVariable) ||     (!uint.TryParse(myStringVariable, out parsedId)) ) {//..show error message} 

This is ugly - How to be more concise?

Note: I know about extension methods, but I wonder if there is something built-in.

like image 251
Marcel Avatar asked Aug 15 '13 11:08

Marcel


People also ask

What does |= mean in C?

The ' |= ' symbol is the bitwise OR assignment operator.

What is '~' in C programming?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

What is an operator in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What is the use of in C?

In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more.


2 Answers

You could use char.IsDigit:

     bool isIntString = "your string".All(char.IsDigit) 

Will return true if the string is a number

    bool containsInt = "your string".Any(char.IsDigit) 

Will return true if the string contains a digit

like image 65
DGibbs Avatar answered Oct 22 '22 08:10

DGibbs


Assuming you want to check that all characters in the string are digits, you could use the Enumerable.All Extension Method with the Char.IsDigit Method as follows:

bool allCharactersInStringAreDigits = myStringVariable.All(char.IsDigit); 
like image 36
dtb Avatar answered Oct 22 '22 07:10

dtb