我正在尝试获取YouTube视频的观看次数,但我的代码存在问题,我没有使用YouTube API!
我首先获取源代码并在尝试获取视图count_但我的问题是我得到startIndex can not be greater than the length of the string
在
string extract = source.Substring(source.IndexOf(key) + i);
//
public string SearchY(RichTextBox richt, string key, int i, string stop)
{
string source = richt.Text;
string extract = source.Substring(source.IndexOf(key) + i);
string result = extract.Substring(0, extract.IndexOf(stop));
return result;
}
// get views
string views = SearchY(richTextBoxSC, "watch-view-count", 19, "</");
labelViewsCount.Text = views;
//获取源代码
string url = textBoxLink.Text;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
richTextBoxSC.Text = sr.ReadToEnd();
答案 0 :(得分:0)
此行中存在问题string extract = source.Substring(source.IndexOf(key) + i);
某种程度上IndexOf(Key) + i
大于字符串source
的长度。因此,您应该在执行substring
int _StartIndex = source.IndexOf(key) + i;
string extract = _StartIndex < source.Length ? source.Substring(_StartIndex) : source;
上面的代码只检查source.IndexOf(key) + i
的值是否小于字符串source
的长度,如果是,则执行旧操作,否则只需将整个文本复制到变量extract
,您可以在: source
在执行string result = extract.Substring(0, extract.IndexOf(stop));
操作之前,您应在应用类似验证的下一行substring
中发生同样的问题。所以who; e函数应该改为:
public string SearchY(RichTextBox richt, string key, int i, string stop)
{
string source = richt.Text;
int _StartIndex = source.IndexOf(key) + i;
string extract = _StartIndex < source.Length ? source.Substring(_StartIndex) : source;
string result = extract.Substring(0, extract.IndexOf(stop));
int _Length = extract.IndexOf(stop);
result = _Length > extract.Length ? extract.Substring(0, _Length) : extract;
return result;
}
答案 1 :(得分:0)
SubString有两个构造函数
- String.SubString(int startIndex)
- String.SubString(int startIndex,int length)
醇>
现在,在您的情况下,您正在使用两者
string extract = source.Substring(source.IndexOf(key) + i);
string result = extract.Substring(0, extract.IndexOf(stop));
问题出现在你的第一个电话中,你只是定义起始索引的值,它可能大于字符串的长度,即来源
要解决您的问题,请首先使用 source.IndexOf(key)+ i 检查来源的长度,然后执行必要的操作。例如:
int startIndex = source.IndexOf(key) + i;
string extract = source; //By default extract is equal to source
//If startIndex of source is less then length of source string then only perform subString operation
if(startIndex < source.Length)
extract = source.Substring(source.IndexOf(key) + i);