发短信.子字符串/文本.索引并不总是返回正确的值

本文关键字:返回 字符串 索引 文本 | 更新日期: 2023-09-27 18:30:34

当我在做文本时。子字符串它并不总是返回正确的值,具体取决于表达式在我正在搜索的文本中的位置。

例如,我在文件内容上有一个 text.substring,我基本上想获取将在文件中的任何位置指定的 URL,但 URL 的最后一部分将始终不同。它将采用http://myURL:1234/My/Folder/Here

所以这是我的代码:

try
{ 
    string text = File.ReadAllText(Path.Combine(textFilePath.Text,filename));
    string FoundName = text.Substring(text.IndexOf("http://", 0) + 7, text.IndexOf(":1234/", 0) - 7);
    if (!listBox4.Items.Contains(FoundName))
    {
        listBox4.Items.Add(FoundName);
    }
}

现在,如果 URL 存在于文件的开头(位置 0),那么它就可以正常工作。

如果它存在于文件的其他任何位置,例如位置 44,则FoundName字符串返回:

myURL:1234/My/Folder/Here而不是:myURL

如果它存在于位置 0,则返回正确的 myURL。

任何建议都会很棒。

谢谢!

发短信.子字符串/文本.索引并不总是返回正确的值

string.SubString将长度作为其第二个参数,而不是索引:

int start = text.IndexOf("http://", 0) + 7;
int end = text.IndexOf(":1234/", 0);
string FoundName = text.Substring(start, end - start);

你需要:

string foundName = text.Substring(
    text.IndexOf("http://") + 7,
    text.IndexOf(":1234/") - text.IndexOf("http://") - 7
    );

或者使用临时变量:

int idxDomainStart = text.IndexOf("http://") + 7;
string foundName = text.Substring(idxDomainStart,
    text.IndexOf(":1234/") - idxDomainStart);