Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to delete the first character of a string

Discussion in 'Scripting' started by YourDiscordKittenUWU, Nov 16, 2022.

  1. YourDiscordKittenUWU

    YourDiscordKittenUWU

    Joined:
    Nov 16, 2022
    Posts:
    2
    Ive been using
    string = string.Substring(1);
    But I get a compiler error that says startindex cannot be longer than length of string.
    Can anyone show me the propper way to eliminate the first character of my string. Thanks in advance.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,962
    string
    is a reserved keyword. Are you using a proper variable name?

    If you are, then perhaps you need to check the
    .Length
    of the string before trying to grab parts of it that don't exist?

    Keep in mind "compiler error" means "something is wrong with the code, it cannot be run."

    A "runtime error" is something like nullref error or the "startindex cannot be longer than length of string." error.

    Those are two vastly different types of errors but they show in the same log.
     
  3. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    Code (CSharp):
    1.   string K = "HELLO";
    2.   Debug.Log(K.Substring(1));
    works for me.

    you must be having a length of a string be ""; One that is asked of the substring. So why not before asking ask if the string is at least of length.
     
    Last edited: Nov 16, 2022
  4. YourDiscordKittenUWU

    YourDiscordKittenUWU

    Joined:
    Nov 16, 2022
    Posts:
    2
    By string I did meant a placeholder for a public string called displayed in my script. right now the code looks like this
    Code (CSharp):
    1. if (displayed.Length > 1)
    2.                 {
    3.                     displayed = displayed.Substring(1);
    4.                 }
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,962
    This is an OBOB (off by one bug)

    if you pass in "K" it will return "K"

    I think you want
    >= 1