pcreyght
pcreyght

Reputation: 211

Substring interpolation

Is it possible to do a string interpolation formatting a substring of a string?

I have been searching the Microsoft documents about string interpolation but cannot get a working sample done. reference.

Currently I have :

var description = "the quick brown fox";
var result = $"{description.Substring(0, description.Length < 10 ? description.Length : 10)} jumps..",

using string interpolation I would ideally like to use:

var description = "the quick brown fox";
var result = $"{description:10} jumps..",

editted

I would expect the output of result to be :

The quick  jumps..

Upvotes: 1

Views: 2089

Answers (3)

rePhat
rePhat

Reputation: 393

You can use ranges (C# 8):

var description = "the quick brown fox";
var result = $"{description[..10]} jumps..";

Upvotes: 6

pcreyght
pcreyght

Reputation: 211

As the question was:
"Is it possible to do a string interpolation formatting a substring of a string?"
In such a manner:

var result = $"{description:10} jumps..",

The answer given from @JohnSkeet and @JeroenMostert was most acurate:
"No, it is not possible."

There are various ways to simplify the call. thanks for @PiotrWojsa for pointing that out. however that doesnt involve the interpolation part..

Upvotes: 2

Piotr Wojsa
Piotr Wojsa

Reputation: 948

You can use Take method:

description.Take(10)

Unfortunately, this method returns IEnumerable which cannot be directly converted to string (ToString method would return name of type as usually when using it on IEnumerable). You can't create string using it, because string constructor requires array of chars, so the easiest solution will be:

new string(description.Take(10).ToArray())

Still, such code makes it harder to read if you want to use it few times, so you can create extension method:

public static string TakeFirst(this string text, int number)
{
    if (text == null)
        return null;

    return new string(text.Take(number).ToArray());
}

Then you can just use it:

$"{description.TakeFirst(10)} jumps..";

EDIT: As mentioned in comments, because of allocation of array each time this method is called, there might occur serious performance issues. You can avoid them by implementing TakeFirst method using Substring instead of Take(x).ToArray() solution.

Upvotes: 1

Related Questions