Limitar la longitud máxima de una cadena

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

Estoy usando GUI.TextField to get the string from the user.

preguntado el 15 de mayo de 13 a las 03:05

If your UI element has a maxlength property, use that. Otherwise validate the length and/or use stringValue.Substring(0, desiredLength) if it exceeds your limit. -

@chris you should make that an answer -

@Kevin, Just did. I'm not familiar with Unity, and it took me a little bit to realize that the Unity tag meant I should be searching that instead of Windows Forms or something :p I also called it a constructor before I realized it was a function. -

2 Respuestas

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.

contestado el 15 de mayo de 13 a las 10:05

Careful in that setter. If I send in "hello world", the truncation will fall on its head. - antonio pegrama

@user414076 is right. Your setter needs a check on the length of the string, otherwise it will fail if the length of the string is less than 20. Probably not what OP wanted - Kevin

The basic concept of this worked for me i just changed around and it works fine. - Dillyo09

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

contestado el 15 de mayo de 13 a las 04:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.