Checking for numbers in a a string
#1

Hey!

As stupid as it may sound, I've forgotten the way of checking numbers in a string.

For e.g: Ilove1234(contains number)

I've used "IsNumeric" but it only identifies numbers and leaves the string. I've tried several different ways but no positive result.

Looking forward to replies
Reply
#2

Quote:
Originally Posted by ZBits
Посмотреть сообщение
Hey!

As stupid as it may sound, I've forgotten the way of checking numbers in a string.

For e.g: Ilove1234(contains number)

I've used "IsNumeric" but it only identifies numbers and leaves the string. I've tried several different ways but no positive result.

Looking forward to replies
There are two ways to do so.
You can:

1. Use Regex
Why? Because it's simple as hell, and safes loads of time. Well, at least as far as You are familiar with regex syntax..

Here is the plugin I use and recommend: Regular expression 0.2

Now, you can do something like this:
pawn Код:
if(regex_search("Abcd1234", "[0-9]+"))
        printf("Contains digits.");
    else
        printf("No digits found!");
[0-9]+ means that regex will search for any pattern in string (Abcd1234) that contains one or more characters from 0 to 9. In this case, server will print out - obviously - "Contains digits"

2. DIY!

This algorithm is pretty simple. At the beggining, assume that text has no digits.
Now iterate through every character in the string and check, if character with index i is >= 48 and <= 57. If yes, then make your algorithm return true which will mean - in our convection - that digit was found. It is not necessary to continue iterating through other characters, because it's complete waste of time. For example, would you continue iteration for such string after character in index of 2?
Код:
AB3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALOLTHISTEXTISSOLONGBBBBBBBBBBBBBCOULDYOUFINDTHEPATTERNEEEEEEEEEILOVEJUSTYNAOMG
Simple as that

And.. why >= 48 and <= 57? Because You are iterating through CHARACTERS encoded in ASCII, not through VALUES. Digits: 0,1,2,..,8,9 are 48, 49,..,56,57 in ASCII, but You should be aware of that.

Greetings
Reply
#3

Thank you for explaning. Problem has been fixed
Reply
#4

EDIT: never mind, posted a little too late.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)