7
I have a scenario where I have set the maximum size of a field. I want to cut that amount to the limit. I am doing this through the Substring
, but returns an error when I have a character of smaller size.
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.Argued tofrangeexception: Index and length must refer to a Location Within the string. Parameter name: length]
Em figured that C# would ignore the string size when cutting it with Substring
, but it wasn’t quite as I thought.
Is there a simple C# method to truncate a string to a given size?
Good. I saw an answer somewhere that taught using the
Math.Min
– Wallace Maxters
@Wallacemaxters yes, the
Math.Min
will return the lower of its two arguments, ie if its string is less than the limit it will return it.– Marconi
Your code looks a lot like this
– Jéf Bueno
@LINQ font added.
– Marconi