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
Subscribe to:
Post Comments (Atom)
11 comments:
James
Couldn't you just do
if myString.Length < 10
James
Couldn't you just do
if myString.Length > 10
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
Thanks this was handy :)
Thanks / it was helpful for me too!
Damian
it's helpful
www.oracledba.in
www.bwtrp.com
www.richonet.com
Great tip, thanks dude
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;
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);
Very good. There is a solution very elegant using LINQ
here.
Post a Comment