Dillyo09
Dillyo09

Reputation: 113

Limiting the maximum length of a string

I need to prevent a string from exceeding a certain length and, if it does, truncate the last part of the string.

I'm using GUI.TextField to get the string from the user.

Upvotes: 0

Views: 5545

Answers (3)

GlitchDev
GlitchDev

Reputation: 36

I think this is the simplest it can get, because I was able to fit it into one line.

(([STRING].Length > [MAX-LENGTH(int)]) ? [STRING].Substring(0, [MAX-LENGTH(int)]) : [STRING])

So as an explaination, first it checks if the string is longer than 10 characters, if so it limits the string with Substring and if not, it just takes the whole string.

Some brackets may be unnecessary, but for my purposes, it was what I needed.

Anyways, hope this helps:)

Upvotes: 0

Yuck
Yuck

Reputation: 50825

Wrap it with a property to handle truncation:

public SomeClass {
    private const int MaxLength = 20; // for example
    private String _theString;

    public String CappedString {
        get { return _theString; }
        set {
            _theString = value != null && value.Length > MaxLength
                ? value.Substring(0, MaxLength)
                : value;
        }
    }
}

You can apply this in whatever class needs to implement it. Just carry over the private field, the constant, and the property CappedString.

Upvotes: 5

Qaz
Qaz

Reputation: 61900

GUI.TextField lets you pass a max length in. You have two to choose from:

static function TextField (position : Rect, text : String, maxLength : int) : String
static function TextField (position : Rect, text : String, maxLength : int, style : GUIStyle) : String

Upvotes: 4

Related Questions