question

BitSmithy-4663 avatar image
0 Votes"
BitSmithy-4663 asked ·

[UWP] How to check if string equals to "_n_"

Hello,


How to check if string equals to expresion showed in post title, where n is number (1,2,3,4,5,6, etc).

Note, I dont want chceck if string contains such expresion, I need to konow if the string exactly equals to expresion.

windows-uwp
· 1
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Maybe I didn't get your purpose but can you just use this:

 if (yourString == $"_{n.ToString()}_")
 {
 }

or

 if (yourString.Equals($"_{n.ToString()}_")
 {
 }

or

 if (string.Equals(yourString, $"_{n.ToString()}_"))
 {
 }



0 Votes 0 ·

1 Answer

RichardZhang-MSFT avatar image
0 Votes"
RichardZhang-MSFT answered ·

Hello,​

Welcome to our Microsoft Q&A platform!

According to your needs, you want the string to be tested to fully conform to the form _n_, with no extra strings before and after. This situation can be solved using regular expressions:

 var regex = new Regex(@"^_\d+_$");
 if(regex.IsMatch(inputString))
 {
 // do something
 }



Update

May I know the language you are using? I implemented it using C#.

Regular expressions have a large overhead on system resources. If there are no special requirements, you can consider this method:

 public bool IsMatchNeeds(string inputString)
 {
     if (inputString.Length < 3)
         return false;
     bool isFirst = inputString.First().Equals("_");
     bool isLast = inputString.Last().Equals("_");
     if (isFirst && isLast)
     {
         string numberString = inputString.Replace("_", "");
         bool isNumber = int.TryParse(numberString, out int num);
         return isNumber;
     }
     return false;
 }

Usage

 if(IsMatchNeeds(inputString))
 {
     // do something...
 }

There are several ways to check if a string is a number. In addition to the regular expressions mentioned earlier, there are the following methods:

1. Enumerable.All

 bool isNumber = numberString.All(p => char.IsDigit(p));

2. Enumerable.Any

 bool isNumber = !numberString.Any(p => p < '0' || p > '9');

3. int.TryParse

 bool isNumber = int.TryParse(numberString, out int number);

4. for-each loop

 bool isNumber = true;
 foreach (var p in numberString)
 {
     if (p < '0' || p > '9')
     {
         isNumber = false;
         break;
     }   
 }

Thanks.

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.