¿Qué método en la clase String devuelve solo los primeros N caracteres?


Me gustaría escribir un método de extensión a la clase String para que si la cadena de entrada a es más larga que la longitud proporcionada N, solo se muestren los primeros caracteres N.

Así es como se ve:

public static string TruncateLongString(this string str, int maxLength)
{
    if (str.Length <= maxLength)
        return str;
    else
        //return the first maxLength characters                
}

¿Qué método String.*() puedo usar para obtener solo los primeros caracteres N de str?

Author: Majid, 2010-08-25

10 answers

public static string TruncateLongString(this string str, int maxLength)
{
    if (string.IsNullOrEmpty(str))
        return str;
    return str.Substring(0, Math.Min(str.Length, maxLength));
}
 318
Author: Paul Ruane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 22:15:35
string truncatedToNLength = new string(s.Take(n).ToArray());  

Esta solución tiene una pequeña ventaja en que si n es mayor que s. Longitud, todavía hace lo correcto.

 51
Author: Matt Greer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-25 14:25:00

Puede usar LINQ str.Take(n) o str.SubString(0, n), donde este último lanzará una excepción ArgumentOutOfRangeException para n > str.Length.

Tenga en cuenta que la versión LINQ devuelve un IEnumerable<char>, por lo que tendría que convertir el IEnumerable<char> a string: new string(s.Take(n).ToArray()).

 27
Author: theburningmonk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-15 10:14:17

Siempre que tengo que hacer manipulaciones de cadenas en C#, echo de menos las buenas y viejas funciones Left y Right de Visual Basic, que son mucho más simples de usar que Substring.

Así que en la mayoría de mis proyectos de C#, creo métodos de extensión para ellos:

public static class StringExtensions
{
    public static string Left(this string str, int length)
    {
        return str.Substring(0, Math.Min(length, str.Length));
    }

    public static string Right(this string str, int length)
    {
        return str.Substring(str.Length - Math.Min(length, str.Length));
    }
}

Nota:
La parte Math.Min está ahí porque Substring lanza un ArgumentOutOfRangeException cuando la longitud de la cadena de entrada es menor que la longitud solicitada, como ya se mencionó en algunos comentarios en anteriores respuesta.

Uso:

string longString = "Long String";

// returns "Long";
string left1 = longString.Left(4);

// returns "Long String";
string left2 = longString.Left(100);
 6
Author: Christian Specht,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-27 05:32:28

Simplemente:

public static String Truncate(String input,int maxLength)
{
   if(input.Length > maxLength)
      return input.Substring(0,maxLength);
   return input;
}
 5
Author: Majid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-24 11:20:24
public static string TruncateLongString(this string str, int maxLength)
{
    return str.Length <= maxLength ? str : str.Remove(maxLength);
}
 4
Author: kbrimington,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-25 14:25:30

Si estamos hablando de validaciones también por qué no hemos comprobado las entradas de cadena nula. Ninguna razón específica?

Creo que debajo de way help ya que IsNullOrEmpty es un método definido por el sistema y los operadores ternarios tienen complejidad ciclomática = 1 mientras que if() {} else {} tiene valor 2.

    public static string Truncate(string input, int truncLength)
    {
        return (!String.IsNullOrEmpty(input) && input.Length >= truncLength)
                   ? input.Substring(0, truncLength)
                   : input;
    }
 4
Author: sunnytyra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-20 09:10:46

Agregué esto en mi proyecto solo porque donde lo estoy usando es una alta probabilidad de que se use en bucles, en un proyecto alojado en línea, por lo tanto, no quería ningún bloqueo si podía administrarlo. La longitud se ajusta a una columna que tengo. Es C # 7

Solo una línea:

 public static string SubStringN(this string Message, int Len = 499) => !String.IsNullOrEmpty(Message) ? (Message.Length >= Len ? Message.Substring(0, Len) : Message) : "";
 1
Author: Richard Griffiths,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-18 15:14:38
substring(int startpos, int lenght);
 0
Author: Tokk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-25 14:25:02

Cadena.Subcadena (0, n); / / 0-índice de inicio y n-número de caracteres

 -4
Author: Jagan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-30 17:50:08