checking numbers in strings
Hi. first of all i'm beginner.
i'm using c# and i need help about this problem. i need to check if the first part of an string Variable is equel to for example "Hello" and Its continuation are numbers(if it continued by numbers. any number) do something. now i know for the first part we have stringVar.StartsWith() , but what about the numbers part? do we have any symbol in strings like #?&$ for representing numbers or any methods? help me please what code should i use?
imagination:
if(stringVar.StartsWith("Hello") && numbers check part)
{
do something
}
else
{
do something else
}
think our string variable is "Hello754".
note: the optimized Performance for this part of my game is very important and don't tell me about going through too many loops and arrays or...
I welcome and appreciate any help :)
Answer by afshin_a_1 · Jan 31, 2017 at 05:10 AM
what about this? :) since my question was under moderator review too long, i had time to search in string methods and write this code. this is working perfectly to me:
int result;
if(stringVar.StartsWith("Hello") && int.TryParse(stringVar.Substring(5), out result))
{
Debug.Log("i'm Hello with my numbers friends");
}
hope it helps anyone else.
thank you very much @ErikHallmarkDev . but i think i find this better as i don't know what are Regular expressions. what's your idea about it?
That solution should work very well. But if I remember correctly both StartsWith
and TryParse
are running regex in the background. So by using your own expression you could cut down on the number of function calls. But that would be a almost unnoticeable performance enhancement, so your solution is fine as is.
Answer by ErikHallmarkDev · Jan 31, 2017 at 03:40 AM
If I understand what you need, you should be able to achieve this with a Regular expression.
First you'll need to include the System.Text.RegularExpressions namespace.
Then you should be able to run this check on your string
if(Regex.IsMatch("Hello754", @"^Hello[0-9]+") //This will return true if the string is the word "Hello" followed by number characters
If you'd like to learn more about Regex so you can create a system that maybe works more the way you want it to, I'd suggest checking out Daniel Shiffmans series on it.
Your answer
Follow this Question
Related Questions
Is it possible to have 2 references in an array? 1 Answer
Accesing specific int from inspector 2 Answers
Checking if a list has an object - Error 1 Answer
Storing input to array 1 Answer
Attack delay not working correctly 1 Answer