How to put Character limit in Text (script)

Asked

Viewed 731 times

0

I would like to limit the text that appears to the user... Inputfield for the user to write the text ,and make the final text receive the text from Inputfield... (wanted to add reticence ( ... ) at the end of the text also, indicating continuity).

inserir a descrição da imagem aqui

  • It always has a fixed size this field?

1 answer

0


We can assemble an extension method that does this and can be called more easily

// Recebe texto e o tamanho máximo da string
public static string Truncar(this string texto, int max)
{
    // Checa se o tamanho do texto é menor ou igual ao tamanho maximo
    // Se for menor, vai retornar apenas o texto
    // Se for maior, vai cortar a string com base na quantidade de caracteres e acrescentar o '...'
    return texto.Length <= max? texto: texto.Substring(0, max) + "...";
}

// Define tamanho máximo
int max = 10;
// Chama método de extensão passando a quantidade máxima como parâmetro
string textoTruncado = texto.Truncar(max);
  • 1

    Do not answer only with code. Try to explain your reasoning so that it is easy to understand by any reader.

  • You’re right, @Isac, it’s my fault I didn’t comment on the code. Updated answer

  • Good answer. Just for reference, in English this is called "Ellipsis" (for example, in Windows Forms has even property to do it automatically). I just suggest setting a default value for the variable max, so to speak texto.Truncar does not necessarily need to pass the maximum value. Other detail even more important is to explain what extension is. AP may not know that you need to save this code with a specific signature. I already gave you my +1, but please improve that part, okay?

  • 1

    References on extension methods: 1 and 2.

  • 1

    @Luizvieira I will read this documentation you indicated and assemble a more complete reply, thanks for the feedback =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.