What is the way to truncate a string in Csharp?

Asked

Viewed 957 times

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?

2 answers

9


Just check if the string size is menor/igual to the limit, use a 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 exceeding 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 on any string:

 texto1.Truncate(limite);

How do I truncate a . NET string?

  • 1

    Good. I saw an answer somewhere that taught using the Math.Min

  • @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.

  • Your code looks a lot like this

  • 1

    @LINQ font added.

5

Why not create an extension method and be happy forever? You can read about them at 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 on . NET Fiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.