简体   繁体   English

C#子字符串抛出异常

[英]C# substring throws an exception

This is my code:这是我的代码:

private string title(string pth) //I'm passing a path
{
    pth = System.IO.Path.GetFileNameWithoutExtension(pth); // I need an exact filename with no extension
    return pth.Substring(pth.IndexOf('-')+1, pth.Length).Trim(); // trying to return everything after '-'
}

It throws an exception.它抛出异常。 I have no idea why.我不知道为什么。 It's an extremely easy way to get the title from filename, but it's not working.这是从文件名中获取标题的一种极其简单的方法,但它不起作用。

I've tried pth.Length-1 , but it's not working either.我试过pth.Length-1 ,但它也不起作用。

You're using the version of the String.Substring method that allows you to specify the number of characters you wish to extract. 您正在使用String.Substring方法的版本,该版本允许您指定要提取的字符数。

However, you're providing the length parameter as the entire length of the string itself -- hence the ArgumentOutOfRangeException . 但是,您要提供length参数作为字符串本身的整个长度-因此是ArgumentOutOfRangeException

If you use this version of String.Substring , you can provide a single parameter ( startIndex ) and you'll automatically get the rest of the string, starting at the index you provide. 如果使用此版本的String.Substring ,则可以提供一个参数( startIndex ),然后自动从提供的索引处获取其余的字符串。

So you can change your code from this: 因此,您可以从此更改代码:

return pth.Substring(pth.IndexOf('-')+1, pth.Length).Trim();

To this: 对此:

return pth.Substring(pth.IndexOf('-')+1).Trim();

Substring(int index, int length) , the length should be the length of the substring, not the length of the entire string. Substring(int index, int length)length应该是子字符串的长度,而不是整个字符串的长度。

You want: 你要:

int index = pth.IndexOf('-');
return pth.Substring(index + 1, pth.Length - index - 1);

the problem is that you are trying to retrieve the substring that is shorter than the length you specified. 问题是您正在尝试检索比您指定的长度短的子字符串。 Also, if the character '-' is at the end of the string, you will get the exception because the index+1 will be outside of the string. 另外,如果字符'-'位于字符串的末尾,则将获得异常,因为index+1将在字符串之外。 This will help: 这将有助于:

private string title(string pth) //I'm passing a path
    {
        pth = System.IO.Path.GetFileNameWithoutExtension(pth); // I need an exact filename with no extension
        string retStr = string.Empty;
        if(pth.IndexOf('-')<pth.Length-1)
        {
              retStr = pth.Substring(pth.IndexOf('-')+1).Trim(); // trying to return everything after '-'
        }
        return retStr;
    }

I'd recommend using a Regular Expression in this case. 我建议在这种情况下使用正则表达式。 Something like: 就像是:

private static string title(string pth)
{
   pth = System.IO.Path.GetFileNameWithoutExtension(pth); // I need an exact filename with no extension
   Match m = Regex.Match(pth, @".*\-(?<suffix>.*)$");

   Group suffix = m.Groups["suffix"];
   return suffix.Success ? suffix.Value : pth;
}

Much cleaner. 干净得多。

I don't know what your exception is, but I'm assuming that - doesn't exist in your string. 我不知道您的例外是什么,但我假设这-您的字符串中不存在。

If you review the documention for String.IndexOf here , you'll see: 如果在此处查看String.IndexOf的文档,您将看到:

The zero-based index position of value if that string is found, or -1 if it is not 如果找到该字符串,则从零开始的索引位置;如果未找到,则返回-1

When you do a subString with a -1 start index, it will throw an exception. 当您使用-1开始索引创建subString时,它将引发异常。

I would check for the existence of - first, then if found do your substring: 我会先检查-的存在,然后如果找到,则执行子字符串:

if(pth.IndexOf('-') != -1)
{
    //Substring code
}

First off, you should tell us what your exception is. 首先,您应该告诉我们您的例外情况。 that will help 那会有所帮助

pth.Substring(pth.IndexOf('-')+1, pth.Length)  

looks like it will throw an exception because it will try to take a substring beyond the length. 看起来会抛出异常,因为它将尝试使用超出长度的子字符串。

try 尝试

pth.Substring(pth.IndexOf('-')+1)

instead 代替

The second parameter to the String.Substring method is the length of the substring. String.Substring方法的第二个参数是子字符串的长度。 The length of the substring in this case should always be less than the length of the pth string. 在这种情况下,子字符串的长度应始终小于第pth字符串的长度。 You probably meant to do this: 您可能打算这样做:

private string title(string pth) //I'm passing a path
{
    pth = System.IO.Path.GetFileNameWithoutExtension(pth);
    return pth.Substring(pth.IndexOf('-')+1, pth.Length - pth.IndexOf('-') - 1).Trim();
}

you need to change your code like this: 您需要像这样更改代码:

private string title(string pth) //I'm passing a path
{
  pth = System.IO.Path.GetFileNameWithoutExtension(pth);
  var indexOfDash = pth.IndexOf('-') + 1; // Add this line
  return pth.Substring(indexOfDash, pth.Length - indexOfDash).Trim();
}

You can use LINQ as below: 您可以按以下方式使用LINQ:

string someString = "abcde";
string subStr = string.Join("", someString.Take(240));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM