C#使用搜索请求打开Goog​​le搜索

时间:2013-12-06 02:42:30

标签: c# string

我有一个InputTextbox,其中包含文本,如:

“搜索谷歌测试”

这是我目前的代码:

String searchRequest = InputTextbox.Text;
searchRequest = searchRequest.SubString(searchRequest.IndexOf("for ") + 4, searchRequest.Length-1);

System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + searchRequest);

我要做的是在“InputTextbox.Text”中搜索单词“for”,并使用其后的任何内容作为搜索词。

有人可以告诉我这件事我做错了吗。

3 个答案:

答案 0 :(得分:2)

SubString中有一个错误。第二个参数是子字符串的长度,而不是子字符串结尾的索引。您需要将其更改为:

searchRequest.SubString(searchRequest.IndexOf("for ") + 4, searchRequest.Length-1 - (searchRequest.IndexOf("for ") + 4));

如果这是有道理的。

我会避免在这里使用子字符串,因为它可能是非常不可预测的。例如,如果未在文本框中键入“for”,则会出现错误,如果输入了两个“for”,我甚至不知道会发生什么。您应该尝试使用RegExp(http://www.regular-expressions.info/)代替:

        String searchRequest = InputTextbox.Text;
        searchRequest = new System.Text.RegularExpressions.Regex("(?<=for ?).+$").Match(searchRequest).Value;

        System.Diagnostics.Process.Start("http://www.google.com.au/search?q=" + System.Uri.EscapeDataString(searchRequest));

请注意,我已从process.start例程中删除了“iexplore”位。这对于使用Internet Explorer的人来说没问题,但最好不要在此处指定浏览器,以便可以使用默认浏览器。另请注意,我使用过System.Uri.EscapeDataString。如果用户在搜索框中输入&符号,这将覆盖您。

答案 1 :(得分:0)

如果错误显示"StartIndex cannot be less than zero",那么这里可能会出现问题:

searchRequest.Length-1

例如,searchRequest.Length可能为零,您从中减去1。

答案 2 :(得分:0)

问题:您提供完整的String Length作为Substring()功能的第二个参数。
解决方案:您应该将字符串Length(字符串中的字符数extracted)作为Parameter的第二个Substring()提供  功能。

来自MSDN

Substring()语法
  

Substring(Int32,Int32):从此实例中检索子字符串。   子字符串从指定的字符位置开始并具有   指定长度

试试这个:

String searchRequest = "search google for test";
int index = searchRequest.IndexOf("for ") + 4;
searchRequest = searchRequest.Substring(index,searchRequest.Length-index);

System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + searchRequest);