2023-12-05, 10:03 AM
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;
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");
}
}