0

My string is delete filename (filename )which i would give at run time this string is str3 I want only the filename(no matter what length it is). Here is my code:

int len = str3.Length;
string d = str3.Substring(6,len-1);// 6 for delete index and to get rest word is len -1
Console.Write(d);

But It is throwing me an exception.

4
  • 4
    (1) Why was this tagged Java? (2) what exactly is the input string? (3) what exactly is the exception. Commented Feb 28, 2012 at 15:02
  • 4
    First, when you say "it is throwing an exception", always post the exception information. Secondly, check the second parameter to the Substring method, it is not the index to stop at, it is the number of characters to copy. You can't copy that many characters (len-1) from the 6th position in the string. Commented Feb 28, 2012 at 15:03
  • I am getting ArgumentOutOfRangeException Commented Feb 28, 2012 at 15:03
  • I will enter delete <filename>(this filename could be any lenght).Now by using substring . I just want filename Commented Feb 28, 2012 at 15:05

4 Answers 4

4

Substring expects the length of the rest of the string (ie, the number of characters to grab). Try this:

string d = str3.Substring(6, len-7);

EDIT - As CodeCaster reminded me, if you're grabbing the whole remainder of the string, you don't need to include the length.

string d = str3.Substring( 6 );
Sign up to request clarification or add additional context in comments.

1 Comment

And you can omit the second parameter, since the behaviour of Substring(int) is to include the remainder of the string.
0

Do this

  str3.Substring(6,(len-6));

Second argument is number of characters in the substring, so if you start at index 6 and you want everything after that point you would subtract startindex from the length.

Comments

0

Since you're not telling us what the exception is, I'm going to assume that it's from the length being less than the substring starting point. Before you do

str3.Substring(6,len-6)

you should first check

if (str3.Length > 6)

so it looks like

int len=str3.Length;
if (str3.Length > 6)
    string d = str3.Substring(6,len-6);
Console.Write(d);

Also note that it's len-6 since that refers to the count, not the last index. The second param for String.Substring also isn't necessary. It goes to the end of the String by default as you can read here.

Comments

0

If you only want the file name, just use the GetFileName method of the Path class in the System.IO namespace:

string d = System.IO.Path.GetFileName(str3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.