• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Pawn] Find the number into a text
#1
Hi  !  I need your help.  I want to find the number in a random text.

 For example:

Code:
#include <open.mp> main() {     new randomText.1[50] = " Hi, my name is John and I am 29 years old.";     new randomText.2[50] = " Hey there, I choose the number 17.");     new randomText.3[50] = " I want to be the number 1.");     new Age;      new LottoNr;     new Number;          FindTheNumber(randomText.1, Age);     printf(" Number found: %d", Age);     FindTheNumber(randomText.2, LottoNr);     printf(" Number found: %d", LottoNr);     FindTheNumber(randomText.3, Number);     printf(" Number found: %d", Number); }
  Reply
#2
The best approach is to use a plugin for adding regex functionality to your script. Regex is good at pattern matching, and it is a breeze to find numbers with it.

I have taken in consideration that you might not use regex or that you are not familiar with it, considering you asked this question.

The approach to find a number in a string can be a bit convoluted.

The approach I would do is as follows:

1. Assign the string to a variable, and loop through it.
2. Every time you find a space, check the part of the string that has been looped over (the current word)
3. Check if it is a number. If it is, voila!

Here is an example;
PHP Code:
stock bool:IsNumber(const string[]) { for(new i = 0; string[i] != '\0'; i++) { if(i == 0 && string[i] == '-' && string[i + 1] != '\0') // Allow minus sign at the start continue; if(string[i] < '0' || string[i] > '9') return false; } return true; } // Function to extract the first number (positive or negative) from a string stock ExtractFirstNumber(const input[], &number) { new word[MAX_STRING_LENGTH]; new idx = 0, wordIdx = 0; while(input[idx] != '\0') { // Check for space or end of string if(input[idx] == ' ' || input[idx + 1] == '\0') { if(input[idx + 1] == '\0') { word[wordIdx] = input[idx]; wordIdx++; } word[wordIdx] = '\0'; if(IsNumber(word)) { number = strval(word); // Convert to number return true; // Number found } wordIdx = 0; // Reset for the next word } else { word[wordIdx] = input[idx]; // Build the current word wordIdx++; } idx++; } return false; // No number found } main() { new input[50] = "This is a test string with number -1234 in it"; new number; if(ExtractFirstNumber(input, number)) { printf("First number found: %d", number); } else { printf("No number found in the string"); } }
Away
  Reply
#3
denNorske - the code works perfect ! Thank you !
  Reply