Truncate String on Whole Words in .Net C#

Truncate string on whole words in .NET C#

Thanks for your answer Dave. I've tweaked the function a bit and this is what I'm using ... unless there are any more comments ;)

public static string TruncateAtWord(this string input, int length)
{
if (input == null || input.Length < length)
return input;
int iNextSpace = input.LastIndexOf(" ", length, StringComparison.Ordinal);
return string.Format("{0}…", input.Substring(0, (iNextSpace > 0) ? iNextSpace : length).Trim());
}

How do I truncate a .NET string?

There isn't a Truncate() method on string, unfortunately. You have to write this kind of logic yourself. What you can do, however, is wrap this in an extension method so you don't have to duplicate it everywhere:

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);
}
}

Now we can write:

var someString = "...";
someString = someString.Truncate(2);
2021-09-17 Alternative with suffix and c#8 nullable reference types.
public static class StringExt
{
public static string? Truncate(this string? value, int maxLength, string truncationSuffix = "…")
{
return value?.Length > maxLength
? value.Substring(0, maxLength) + truncationSuffix
: value;
}
}

To write:

"abc".Truncate(2);          // "ab…"
"abc".Truncate(3); // "abc"
((string)null).Truncate(3); // null

How can I truncate my strings with a ... if they are too long?

Here is the logic wrapped up in an extension method:

public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}

Usage:

var s = "abcdefg";

Console.WriteLine(s.Truncate(3));

How to split string preserving whole words?

Try this:

    static void Main(string[] args)
{
int partLength = 35;
string sentence = "Silver badges are awarded for longer term goals. Silver badges are uncommon.";
string[] words = sentence.Split(' ');
var parts = new Dictionary<int, string>();
string part = string.Empty;
int partCounter = 0;
foreach (var word in words)
{
if (part.Length + word.Length < partLength)
{
part += string.IsNullOrEmpty(part) ? word : " " + word;
}
else
{
parts.Add(partCounter, part);
part = word;
partCounter++;
}
}
parts.Add(partCounter, part);
foreach (var item in parts)
{
Console.WriteLine("Part {0} (length = {2}): {1}", item.Key, item.Value, item.Value.Length);
}
Console.ReadLine();
}

Set max length of a string c# but end with whole word

Look for the last space before that position, and cut the string there. If there is no space at all, or if it is too soon in the text, then just cut it at 180 anyway.

string mktText = model.Product.MarketingText;
if (mktText.Length > 180) {
int pos = mktText.LastIndexOf(" ", 180);
if (pos < 150) {
pos = 180;
}
mktText = mktText.Substring(0, pos) + "...";
}

Remove words from string c#

Ok so I figured out how to remove the words through one of my existing functions:

public static string RemoveHTML(string text)
{
text = text.Replace(" ", " ").Replace("<br>", "\n").Replace("description", "").Replace("INFRA:CORE:", "")
.Replace("RESERVED", "")
.Replace(":", "")
.Replace(";", "")
.Replace("-0/3/0", "");
var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
return oRegEx.Replace(text, string.Empty);
}

Trim String by so many characters but do not cut off last word

I use the following method:

''' <summary>
''' Creates a shortend version of a string, with optional follow-on characters.
''' </summary>
''' <param name="stringToShorten">The string you wish to shorten.</param>
''' <param name="newLength">
''' The new length you want the string to be (nearest whole word).
''' </param>
''' <param name="isAbsoluteLength">
''' If set to <c>true</c> the string will be no longer than <i>newLength</i>.
''' and will cut off mid-word.
''' </param>
''' <param name="stringToAppend">
''' What you'd like on the end of the shorter string to indicate truncation.
''' </param>
''' <returns>The shorter string.</returns>
Public Shared Function ShortenString(stringToShorten As String, newLength As Integer, isAbsoluteLength As Boolean, stringToAppend As String) As String
If Not isAbsoluteLength AndAlso (newLength + stringToAppend.Length > stringToShorten.Length) Then
' requested length plus append will be longer than original
Return stringToShorten
ElseIf isAbsoluteLength AndAlso (newLength - stringToAppend.Length > stringToShorten.Length) Then
' requested length minus append will be longer than original
Return stringToShorten
Else
Dim cutOffPoint As Integer

If Not isAbsoluteLength Then
' Find the next space after the newLength.
cutOffPoint = stringToShorten.IndexOf(" ", newLength)
Else
' Just cut the string off at exactly the length required.
cutOffPoint = newLength - stringToAppend.Length
End If

If cutOffPoint <= 0 Then
cutOffPoint = stringToShorten.Length
End If

Return stringToShorten.Substring(0, cutOffPoint) + stringToAppend
End If
End Function

How do I truncate a .NET string?

There isn't a Truncate() method on string, unfortunately. You have to write this kind of logic yourself. What you can do, however, is wrap this in an extension method so you don't have to duplicate it everywhere:

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);
}
}

Now we can write:

var someString = "...";
someString = someString.Truncate(2);
2021-09-17 Alternative with suffix and c#8 nullable reference types.
public static class StringExt
{
public static string? Truncate(this string? value, int maxLength, string truncationSuffix = "…")
{
return value?.Length > maxLength
? value.Substring(0, maxLength) + truncationSuffix
: value;
}
}

To write:

"abc".Truncate(2);          // "ab…"
"abc".Truncate(3); // "abc"
((string)null).Truncate(3); // null

How to display string with maximum of 200 characters & trim the last few charaters till whitespace

You should find the index of the space right before the 200 index. So search for all occurrences and then pick the index of the one the closest to 200. Then use this index to do a Substring and you should be good to go

string myString = inputString.Substring(0, 200);

int index = myString.LastIndexOf(' ');

string outputString = myString.Substring(0, index);

How to truncate or pad a string to a fixed length in c#

All you need is PadRight followed by Substring (providing that source is not null):

string source = ...
int length = 5;

string result = source.PadRight(length).Substring(0, length);

In case source can be null:

string result = source == null 
? new string(' ', length)
: source.PadRight(length).Substring(0, length);


Related Topics



Leave a reply



Submit