Gali
Gali

Reputation: 14953

how to check if my string contain text?

if i have this string:

12345 = true

123a45 = false

abcde = false

how to do it in C#?

Upvotes: 4

Views: 2840

Answers (6)

Felice Pollano
Felice Pollano

Reputation: 33252

Regex.IsMatch(sinput,@"\d+"); 

to match a string containing just digits. If you forgot an optional digit in the question, use this:

Regex.IsMatch("+12345", @"[+-]?\d+");

Upvotes: 6

Joe Enos
Joe Enos

Reputation: 40393

If you want to avoid RegEx, then you can use the built-in char methods:

bool allDigits = s.All(c => char.IsDigit(c));

Upvotes: 3

HuBeZa
HuBeZa

Reputation: 4761

int.TryParse or long.TryParse.

You can also use Regex for any length of number:

if (Regex.IsMatch(str, "^[0-9]+$"))
// ...

Upvotes: 0

John Arlen
John Arlen

Reputation: 6689

int myNumber;
if( int.TryParse(myString, out myNumber) == true )
{
 // is a number and myNumber contains it
}
else
{
 // isn't a number
}

if it's a BIG number, use long or double or.... instead of int.

Upvotes: 0

joshhendo
joshhendo

Reputation: 2004

private bool ContainsText(string input)
        {
            for (int i = 0; i < input.Length; i++)
            {
                if (((int) input[i] >= 65 && (int) input[i] <= 90) || ((int) input[i] >= 97 && (int) input[i] <= 177))
                    return true;
            }

            return false;
        }

Running:

MessageBox.Show(ContainsText("abc").ToString());
MessageBox.Show(ContainsText("123").ToString());
MessageBox.Show(ContainsText("123b23").ToString());

returns True, False, True respectively

Upvotes: 0

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

This is the code for checking only letters in string in C#. You can modify it upto your need.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string MyString = "A @string & and 2.";

            Console.WriteLine(MyString);
            for (int charpos = 0; charpos < MyString.Length; charpos++)
            {
                Console.WriteLine(Char.IsLetter(MyString, charpos));    
            }
            //Keep the console on screen
            Console.WriteLine("Press any key to quit.");
            Console.ReadKey();
        }
    }
}

Upvotes: 0

Related Questions