I have a scenario where I have set the maximum size of a field. I want to cut this value to the limit. I'm doing this through Substring
, but it returns an error when I have a smaller-sized character.
Example:
int limite = 20;
string texto1 = "meu nome é wallace de souza";
string texto2 = "meu nome é wallace";
Console.WriteLine(texto1.Substring(0, limite));
// 'meu nome é wallace d'
Console.WriteLine(texto2.Substring(0, limite));
//Erro: ArgumentOutOfRangeException
The error generated is:
[System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length]
I imagined that C # would ignore the length of the string when cutting it with Substring
, but it was not quite as I thought.
Is there a simple C # method to truncate a string for a given size?