String in Unity using C#

· 1 min read

In Unity, you can either use string or System.String for the string variable.

public class PlayerControl : MonoBehaviour {
    
    void Awake() {
        // define a string
        string s = "foo";
        Debug.Log(s);   // output: foo

        // string format
        s = string.Format("{0} {1}", s, "bar");
        Debug.Log(s);   // output: foo bar

        // to uppercase
        s = s.ToUpper();
        Debug.Log(s);   // output: FOO BAR

        // to lowercase
        s = s.ToLower();
        Debug.Log(s);   // output: foo bar

        // concat two string
        s = string.Concat("foo", "bar");
        Debug.Log(s);   // output: foobar

        // get character from index
        Debug.Log(s[0]);    // output: f

        // ToString() function basically can convert any number to string
        // convert int to string,
        int i = 10;
        s = i.ToString();
        Debug.Log(s);   // output: "10"

        // convert string to int
        s = "100";
        i = int.Parse(s);
        Debug.Log(i);   // output: 100

        s = "abc";
        i = int.Parse(s);
        Debug.Log(i);
        //error FormatException: Input string was not in a correct format.
    }
}