- Home /
Remove Numbers from a String
Hi. I need to remove some numbers from a string.
The string looks something like "XX points", where XX is a number. It can be one or two digits.
I tried things with character arrays and such, but I can't get anything to work. Here's the code I'm working on now (it says that the debug.log returns "array index is out of range" error messages).
if (MainBallPoints != null)
{
string ballvalue = string.Empty;
string currentvalue = MainBallPoints.value.ToString();
for (int i = 0; i < currentvalue.Length; i++)
{
if (((int)currentvalue[i] >= 0) && ((int)currentvalue[i] <= 9))
{
ballvalue += currentvalue[i];
}
}
Debug.Log(ballvalue[1]);
Utility.MainBallScore = int.Parse(ballvalue);
Debug.Log(Utility.MainBallScore);
}
Any advice is very welcome. I also don't feel comfortable casting inside of a for loop, but I'm not sure of a way around that.
Thank you for your time.
Answer by YoungDeveloper · Jan 19, 2014 at 06:12 PM
There are probably ready functions for this. But one way of doing this could be comparing string to ascii table.
This will return a new string without numbers, and set number itself. I didn't test this, but should work.
int num;
string RemoveNumbers(string text){
string newText = "";
string number = "";
for(int i = 0; i < text.Length; i++){
if ((text[i] < 48) || (text[i] > 57)){ //is a char
newText += text[i];
}
else{ //is number
number += text[i];
}
}
num = int.Parse(number);
return newText;
}
I was about to give something like this but then remembered that there should be a regex out there that does it with line. Also, this needs to be checked since I think Unity uses UTF-16 and not ascii (no ascii for sure) but I would think the first byte is just a bunch of 0 so the 48/57 thingy should do.
Hmm, i have posted this type of solutions before and tested them in unity, worked like a charm.
Your answer
![](https://koobas.hobune.stream/wayback/20220613130845im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Find the length of a string in Javascript 1 Answer
How do you set a string while in game ? 2 Answers
Edit a string C# 1 Answer
Using Raycast for RTS game ? 2 Answers
Recovering function from input string 2 Answers