Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minimize length of string in C#

Tags:

string

c#

I want to reduce the length of a string. Like...

This string...

string foo ="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in vehicula nulla. Phasellus libero dui, luctus quis bibendum sit amet";

Becomes this string...

Lorem ipsum dolor sit amet, consectetur adipiscing...

How do I do this? Thanks!

like image 990
Thiago Avatar asked Dec 03 '22 09:12

Thiago


2 Answers

string foo ="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in vehicula nulla. Phasellus libero dui, luctus quis bibendum sit amet";

string small_foo = foo.SubString(0, 50);

Using Substring to get the first 50 characters of the string. http://msdn.microsoft.com/en-us/library/aka44szs.aspx

like image 108
TJHeuvel Avatar answered Dec 21 '22 00:12

TJHeuvel


Code

public string Truncate(string input, int length)
{
    if (input.Length < length) return input;
    int index = input.IndexOf(' ', length);
    return input.Substring(0, index) + "...";
}

...

string foo ="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in vehicula nulla. Phasellus libero dui, luctus quis bibendum sit amet";

string bar = Truncate(foo, 50);
Console.WriteLine(bar);

Output

Lorem ipsum dolor sit amet, consectetur adipiscing...

Instead of

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in vehicula nulla. Phasellus libero dui, luctus quis bibendum sit amet

like image 24
Greg B Avatar answered Dec 20 '22 23:12

Greg B