Legacy Documentation: Version 4.5.0

Script language:

  • JS
  • C#
  • Boo
Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

String

Description

Represents text as a series of Unicode characters.

Unity uses the .Net System.String class for strings. See the Microsoft MSDN documentation for Strings for more details.

Note: In c# string is an alias for System.String. This means that you can use either string or String in your code (if you have added using System to the top of your script.) Note: In Javascript strings are represented using String which you should use in your Unity script code. Here are some basic uses of the String class.

// Javascript
#pragma strict

function Start () { var s : String = "hello"; Debug.Log(s); // prints hello s = String.Format("{0} {1}", s, "world"); Debug.Log(s); // prints hello world s = String.Concat("hello","world"); Debug.Log(s); // prints helloworld s = s.ToUpper(); Debug.Log(s); // prints HELLOWORLD s = s.ToLower(); Debug.Log(s); // prints helloworld

//Debug.Log(s.CharAt(1)); // CharAt not supported, produces compiler error // instead use array syntax below Debug.Log(s[1]); // prints e var c : char = 'x'[0]; // slight odd JS way of specifying a char // 'x' is a string and [0] means first character Debug.Log(s.IndexOf(c)); // prints -1 (s does not contain an x) var i : int = 42; s = i.ToString(); Debug.Log(s); // prints 42

s = "-43"; i = int.Parse(s); Debug.Log(i); // prints -43 var f : float = 3.14159265358979f; s = f.ToString(); Debug.Log(s); // prints 3.141593 (which is an approximation) s = "-7.14159265358979"; f = float.Parse(s); Debug.Log(f); // prints -7.141593 (which is an approximation) }

This example shows how you can examine the String class and see the methods it contains.

// Javascript
#pragma strict

import System; import System.Reflection;

function Start () {

var t : Type = System.String;

// Iterate over all the methods from the System.String class and display // return type and parameters. // This reveals all the things you can do with a String. for (var mi : MethodInfo in t.GetMethods()) { var s : System.String = System.String.Format("{0} {1} (", mi.ReturnType, mi.Name); var pars : ParameterInfo[] = mi.GetParameters(); for (var j : int = 0; j < pars.Length; j++) { s = String.Concat(s, String.Format("{0}{1}", pars[j].ParameterType, (j == pars.Length-1) ? "" : ", ")); } s = String.Concat(s, ")"); Debug.Log(s); } }

Variables

EmptyRepresents the empty string. (Read Only)
LengthGets the number of characters in this instance (Read Only).