What is the way to truncate a string in Csharp?

7

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?

    
asked by anonymous 07.12.2017 / 16:25

2 answers

9

Just check if the string size is menor/igual to the limit, use if ternary.

texto1.Length <= limite ?  texto1 :  texto1.Substring(0, limite); 

Another way is to use Math.Min Method , which returns the smaller of two signed integers, avoiding to exceed the size of your string.

texto1.Substring(0, Math.Min(texto1.Length, limite));

Extensions :

public static class StringExt
{
    public static string Truncate(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Length <= maxLength ? value : value.Substring(0, maxLength); 
    }
}

The good thing about you adding an extension method is that you can use it in any string :

 texto1.Truncate(limite);

How do I truncate the .NET string?

    
07.12.2017 / 16:29
5

Why not create an extension method and be happy forever? You can read about them in Why use C # extension methods?

public static class StringUtilsExtensions
{
    public static string Trunc(this string original, int length)
    {
        return original?.Substring(0, Math.Min(original.Length, length)) ?? "";
    }
}

Executable code

using System;

public class Program
{
    public static void Main()
    {
        string texto1 = "meu nome é wallace de souza";          
        Console.WriteLine(texto1.Trunc(20));
    }
}

public static class StringUtilsExtensions
{
    public static string Trunc(this string original, int length)
    {
        return original?.Substring(0, Math.Min(original.Length, length)) ?? "";
    }
}

See working in .NET Fiddle.

    
07.12.2017 / 16:37