tamaño length know how example array c# arrays string limit

length - C#: ¿Limitar la longitud de una cuerda?



string length c# (11)

Aquí hay otra respuesta alternativa a este problema. Este método de extensión funciona bastante bien. Esto resuelve los problemas de que la cuerda sea más corta que la longitud máxima y también que la longitud máxima sea negativa.

public static string Left( this string str, int length ) { if (str == null) return str; return str.Substring(0, Math.Min(Math.Abs(length), str.Length)); }

Otra solución sería limitar la longitud para que sean valores no negativos, y solo valores negativos de cero.

public static string Left( this string str, int length ) { if (str == null) return str; return str.Substring(0, Math.Min(Math.Max(0,length), str.Length)); }

Esta pregunta ya tiene una respuesta aquí:

Simplemente me preguntaba cómo podría limitar la longitud de una cuerda en C #.

string foo = "1234567890";

Digamos que tenemos eso. ¿Cómo puedo limitar a foo para decir, 5 caracteres?


La única razón por la que puedo ver el propósito en esto es para el almacenamiento de DB. Si es así, ¿por qué no dejar que el DB lo maneje y luego presionar la excepción en sentido ascendente para tratar en la capa de presentación?


Las cadenas en C # son inmutables y, en cierto sentido, significa que son de tamaño fijo.
Sin embargo, no puede restringir una variable de cadena para que solo acepte cadenas de n caracteres. Si define una variable de cadena, se le puede asignar cualquier cadena. Si truncar cadenas (o lanzar errores) es parte esencial de su lógica de negocios, considere hacerlo en el conjunto de propiedades de su clase específica (eso es lo que Jon sugirió, y es la manera más natural de crear restricciones en los valores en .NET).

Si solo quiere asegurarse de que no sea demasiado largo (por ejemplo, al pasarlo como un parámetro a algún código heredado), trunque de forma manual:

const int MaxLength = 5; var name = "Christopher"; if (name.Length > MaxLength) name = name.Substring(0, MaxLength); // name = "Chris"


No puedes. Tenga en cuenta que foo es una variable de tipo string .

Puede crear su propio tipo, decir BoundedString , y tener:

BoundedString foo = new BoundedString(5); foo.Text = "hello"; // Fine foo.Text = "naughty"; // Throw an exception or perhaps truncate the string

... pero no puede evitar que una variable de cadena se establezca en cualquier referencia de cadena (o nulo).

Por supuesto, si tienes una propiedad de cadena, podrías hacer eso:

private string foo; public string Foo { get { return foo; } set { if (value.Length > 5) { throw new ArgumentException("value"); } foo = value; } }

¿Eso te ayuda en lo que sea que sea tu contexto más grande?


Puede evitar la instrucción if si la rellena hasta la longitud a la que desea limitarla.

string name1 = "Christopher"; string name2 = "Jay"; int maxLength = 5; name1 = name1.PadRight(maxLength).Substring(0, maxLength); name2 = name2.PadRight(maxLength).Substring(0, maxLength);

name1 tendrá a Chris

name2 tendrá Jay

No se necesita ninguna declaración para verificar la longitud antes de usar subcadena


Puede extender la clase "cadena" para que pueda devolver una cadena limitada.

using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // since specified strings are treated on the fly as string objects... string limit5 = "The quick brown fox jumped over the lazy dog.".LimitLength(5); string limit10 = "The quick brown fox jumped over the lazy dog.".LimitLength(10); // this line should return us the entire contents of the test string string limit100 = "The quick brown fox jumped over the lazy dog.".LimitLength(100); Console.WriteLine("limit5 - {0}", limit5); Console.WriteLine("limit10 - {0}", limit10); Console.WriteLine("limit100 - {0}", limit100); Console.ReadLine(); } } public static class StringExtensions { /// <summary> /// Method that limits the length of text to a defined length. /// </summary> /// <param name="source">The source text.</param> /// <param name="maxLength">The maximum limit of the string to return.</param> public static string LimitLength(this string source, int maxLength) { if (source.Length <= maxLength) { return source; } return source.Substring(0, maxLength); } } }

Resultado:

limit5 - El q
limit10 - El rápido
limit100 - El rápido zorro marrón saltó sobre el perro perezoso.


Puedes intentarlo así:

var x= str== null ? string.Empty : str.Substring(0, Math.Min(5, str.Length));


Si esto está en una propiedad de clase, podrías hacerlo en el colocador:

public class FooClass { private string foo; public string Foo { get { return foo; } set { if(!string.IsNullOrEmpty(value) && value.Length>5) { foo=value.Substring(0,5); } else foo=value; } } }


Use Eliminar () ...

string foo = "1234567890"; int trimLength = 5; if (foo.Length > trimLength) foo = foo.Remove(trimLength); // foo is now "12345"


foo = foo.Substring (0,5);


string shortFoo = foo.Length > 5 ? foo.Substring(0, 5) : foo;

Tenga en cuenta que no puede usar foo.Substring (0, 5) solo porque arrojará un error cuando foo tenga menos de 5 caracteres.