- Home /
Decreasing Length of a String?
Hey guys, I am trying to make a string adjust perfectly in its length. I am using this code:
if(k.Killer.Length > maxString)
{
k.Killer.Length = Mathf.Clamp(k.Killer.Length, 0, maxString);
k.Killer = k.Killer += "...";
}
The problem is that String.Lenght is read only and cannot be manipulated, anyone know how to change this? I want the amount of characters in the string to equal maxString.
Cheers!
Answer by robertbu · Oct 19, 2013 at 10:09 PM
String.Substring() will do the job. You want the two parameter version so it will:
k.killer = k.killer.Substring(0, maxString);
I want to add to this that Strings are immutable, which means you can't edit them after creating them. The only way to change the value of the string is to assign it to a new string. This is why changing the length doesn't work. The Substring method creates a new string with information from the old one, and returns it, so you can reassign the variable to the result of Substring to get the effect you're looking for.
So substring gets part of a string and allows you to decide which parts? Not bad, thanks for the information!
Answer by MarkHelsinki · May 31 at 08:27 AM
For future people finding this, you can also use string range from the System namespace: So:
nameSub = name[..5];
Where the range is the number of characters you want to keep.
Your answer
Follow this Question
Related Questions
GUI set max amount of characters for Label 1 Answer
Passing a Script Name to a Function 2 Answers
Display text with unknown length? 1 Answer
how to check GUI.TextField Entry 2 Answers
Using Polish characters in OnGUI 1 Answer