losopha
losopha

Reputation: 127

Substring Maximum Length

I have strings of length greater than 150 characters. I want to delete the first 17 characters and leave the rest. I am using the Substring method in ASP.net 4.5 but I get the error message at str0: "System.ArgumentOutOfRangeException".

 public static string extract(string dirinfo)
 {
      Int32 lensub = Convert.ToInt32(dirinfo.Length);
      string str0 = dirinfo.Substring(17, lensub);
      return str0;
 } 

Upvotes: 0

Views: 8624

Answers (4)

Ivan Stoev
Ivan Stoev

Reputation: 205549

I want to delete the first 17 characters and leave the rest.

Then do exactly what you want

string str0 = dirinfo.Remove(0, 17);

Reference: String.Remove Method (Int32, Int32)

public string Remove(int startIndex, int count)

Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.

Upvotes: 0

Nantharupan
Nantharupan

Reputation: 614

string str0 = dirinfo.Substring(17, lensub-17);
return str0;

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98740

Substring(int, int) overload takes length as a second parameter that you want to the rest as you said, not the complete string length.

If your string length is 150, dirinfo.Substring(17, 150) means;

Starts with 17 as a position ant takes 150 character after it.

Which means, your string needs 167 character at least but it does not. That's why you get ArgumentOutOfRangeException.

Just use Substring(int) overload as;

string str0 = dirinfo.Substring(17);

which is described;

Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

By the way, Length is already int, you don't need to parse it.

Upvotes: 6

Steve
Steve

Reputation: 216253

You should remove the constant 17 from the len calculated

 public static string extract(string dirinfo)
 {
      Int32 lensub = Convert.ToInt32(dirinfo.Length);
      string str0 = dirinfo.Substring(17, lensub-17);
      return str0;
 } 

Otherwise the required number of chars to return is more than the remaining length of the string

Of course, (giving credit to the answer from Soner Gönül) you could simplify your method to

 public static string extract(string dirinfo)
 {
      return (dirinfo.Length > 17 ? dirinfo.Substring(17) : "");
 } 

Upvotes: 6

Related Questions