- Home /
How to delete the last character of a string
I've a num pad system in my game where you just click buttons that will return a number in string. Each number you press it adds to a result string that is used for a code.
public void ApplyNumber (string codeNumber) {
resultCode += codeNumber;
curChars++;
if(curChars >= maxChars) {
Reset ();
}
}
This is the function that update the string. Now I'm trying to make another button that have to delete the last char of the string, but I'm clueless on how to do that. Any idea?
Would prefer examplesin c#. Thanks in advance.
Answer by Dave-Carlile · Oct 25, 2012 at 12:38 PM
string value = "abcde";
value = value.Substring(0, value.Length - 1);
The Substring function lets you grab part of a string. The first parameter is the starting position, the second is the length you want. By passing the current string length - 1, you're getting everything but the last character.
I find this solution the most viable, but still i get an error when going in negative, so if I keep deleting the string when reaching < 0 I get an error. I guess I need to put a failsafe in the code to set back to 0 the string when reaching < 0.
Answer by markpdolby · Oct 25, 2012 at 12:48 PM
string s = "test";
s = s.Remove(s.length - 1);
Using something like this should give you the string but with one less character, so in this example s would end up as "tes"
Hope that helps
Answer by Unity_gamer · Oct 25, 2012 at 12:20 PM
Hi Neurological ,
Try Splitting the String Using "Stringname.split" and Save that Value .
// Say the String Is "Unity,3d"
//If you want to split the String with ","
String[] parts = codeNumber.Split(","[0]);
codeNumber = parts[0]; // Here in codeNumber you will get "Unity"
Thanks
It also works, although if you know exacly where you want to trim, use Substring, as Split and For() loops requires a lot of processing and will slow down the game if called too quickly...