Simple String Extensions

This is a very simple string extension that you might need to limit the amount of sentence length.

It is useful in situations where one content area can be used to show full text or just the summary.

Now, you would say I could limit that the sentence length with

myVar.SubString(0,maxLength)

function, but it will chop off the word of a sentense where it will meet the limit

What to do?

Consider the following snippet

public static string LimitSentenceLength(this string s, int maximumLength)
{
//safe type checking
if (s == null)
return null;

//if length of the content is greater than
//maximum length define, then we do some magic
if (s.Length > maximumlength)
{

//split the sentence into individual words
string[] sentence = s.Split(' ');

//initilaize string to return
string toReturn = string.Empty;

//loop through each word in sentense
foreach (string word in sentence)
{
//if the length of return word plus current word plus
//a constant 3 (for "...")    is more than the max
//length define, then add "..." , break the for loop and return
if ((toReturn.Length + word.Length + 3) > maximumlength)
{
toReturn += "...";
break;
}

//if not, then keep on adding words with spaces
toReturn += word + " ";

}

//for loop ends, return modified string
return toReturn;
}

//entered string is shorter than max length define, return original sentence
else
{
return s;
}

}

Code is pretty much self explanatory but I will try to explain this simpleton

1. It checks if string is not null
2. Then it checks that if the length of string is more than maximum limit define in code
2a. If it does, the function does it magic and returns the modified word
2b. Otherwise, it returns the orginal word

To use this extension else where in the code, add namespace of your class and do something like

var myString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tincidunt metus at elit condimentum auctor.";
myString = myString.LimitSentenceLength(20);

Happy coding!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.