Truncating a string...

  • Thread starter Thread starter VM
  • Start date Start date
V

VM

How can I truncate a string? For example, if I have a string containing
"Hello All" but the space reserved for this string is of 4 chars, how can I
truncate it to "Hell"? Would I need to create my own method for this or is
there an exisiting String method that does it?
Thanks
 
Try this,

string myStr = "Hello All"

//remove characters after 4.
myStr = myStr.Remove(4,myStr.Length-4);
 
But string.SubString assumes that the string size I'll be extracting is less
than/equal to the string source. If I extract a substring of size 12 from a
string of 4 chars, it'll throw a runtime exception.
 
With string.Remove I also have to check the size of the string... It's more
or less like the substring.
 
That's correct, it requires two operations if you expect that the string may
be less than the truncated size request:

x.Substring(0, Math.Min(x.Length, size))
 
Back
Top