I'm new to Unity and C# in general, just started using them less than a month ago so I can make a school project. A little background about my project, I'm making a maths game, the specific problem I'm working on is related to taking in the answer of a question through an input box. Since it's maths, each question has only one specific answer, so I thought I could use a regular conditional statement to compare the stored value of the answer with the user's input, that much is fine.
My problem is that I'm considering if someone puts in an input, they'll leave white space at the start or the end or in the middle of the text (for example, if writing a fraction they could write it as "3 / 4" or " 3/4"), and if my statement compares the stored value with their input, it'll say their answer is wrong because there's some white space so it's not the exact same.
I'm aware of the Trim() method in C# but as far as I'm aware it only removes leading and trailing white spaces, nothing in between. Is there an in-built method that allows me to remove white space between characters as well, or is there a way I can do that myself? Thank you very much in advance!
You're right,
string.Trimremoves the spaces before and after,string.TrimStartbefore andstring.TrimEndafter thestring.However, this doesn't remove the spaces in the middle of the
string.The easiest way to remove all the spaces is to replace them by nothing using
string.Replacemethod, where the 1st parameter is an old value, and the 2nd a new one.Here we find all the space characters (
" ") and replace them by nothing (""). This returns astringwith no spaces at all.You can also replace
charsinstead ofstringsusingReplaceoverload, even though it doesn't really matter, as the result stays the same.Additionally, you can implement this kind of method yourself using a
fororforeachloop.