Friday 17 August 2007

Truncating a string in C# - Easy huh?

I had an interesting issue this morning, it sounds really simple... All I wanted to do was make sure that a string was 10 charactors or less. Easy huh? Just use substring!

mystring = "Hello";
string newstring = mystring.substring(0,10)

Wrong!

substring will fail with an exception because mystring doesn't have 10 characters.

Here is a neat solution:

string newstring = mystring.Substring(0, Math.Min(mystring.Length, 10));

James

11 comments:

Anonymous said...

James

Couldn't you just do

if myString.Length < 10

Anonymous said...

James

Couldn't you just do

if myString.Length > 10

Frickley said...

Yes, you could... but I prefer my way as it's a neat & simple 1 liner. You could argue that my way is perhaps a little cryptic.

I guess it's all down to programming style.

Thanks for your comment

J

Garth said...

Thanks this was handy :)

Anonymous said...

Thanks / it was helpful for me too!

Damian

www.oracledba.in said...

it's helpful


www.oracledba.in
www.bwtrp.com
www.richonet.com

Anonymous said...

Great tip, thanks dude

Anonymous said...

You could also just use the ternary operator to keep it on 1 line and not use the Math.min method.

string buddy = (myString.Length > 10) ? myString.subString(0, 10) : myString;

A Booth said...
This comment has been removed by the author.
A Booth said...

Create a String extension like so: -


public static string Truncate( this string target, Int32 maximumLength)
{
return null == target || target.Length <= maximumLength ? target : target.Substring(0, maximumLength);
}


Then you can use it like this: -

string newString = oldString.Truncate(10);

Unknown said...

Very good. There is a solution very elegant using LINQ
here.