【问题标题】:Alternative to using InStr替代使用 InStr
【发布时间】:2015-04-07 09:41:25
【问题描述】:

如何使用不同的函数“InStr” 这是我正在使用的代码并且工作正常,但远离 InStr 是我的目标

i = InStr(1, Hostname, Environment.Newline)

【问题讨论】:

    标签: c# vb.net


    【解决方案1】:

    String.Indexof() 有几个重载:

    Dim jstr = "How much wood could a woodchuck chuck if a woodchuck..."
    
    ' Find a character from a starting point
    ndx = jstr.IndexOf("w"c)             ' == 2 (first w)
    '  or within a range:
    ndx = jstr.IndexOf("o"c, 12)         ' == 15 first o past 12 (cOuld)  
    
    'Find a string
    ndx = jstr.IndexOf("wood")           ' == 9
    ' ...from a starting point
    ndx = jstr.IndexOf("wood", 10)       ' == 22 (WOODchuck)
    ' ...or in part of the string
    ndx = jstr.IndexOf("chuck", 9, 15)   ' -1 (none in that range)
    
    ' using a specified comparison method:
    ndx = jstr.IndexOf("WOOD", StringComparison.InvariantCultureIgnoreCase)  ' 9
    ndx = jstr.IndexOf("WOOD", nFirst, StringComparison) 
    ndx = jstr.IndexOf("WOOD", nFirst, nLast, StringComparison)
    

    还有一个String,LastIndexOf() 方法可以获取字符串中某些内容的最后一次出现,也有各种重载。

    在您附近的 VS 中的 MSDN 或对象浏览器(VIEW 菜单 | 对象浏览器)中可用。

    i = Hostname.Indexof(Environment.Newline, 1)
    

    【讨论】:

    • 由于 Instr 计数从 1 开始但 IndexOf() 是基于 0,我们是否在末尾添加 +1?
    【解决方案2】:

    如果您需要等效的 C# 代码,您可以使用 Microsoft.VisualBasic 程序集中的 Strings 类,因此代码可以如下所示:

    using Microsoft.VisualBasic;
    . . . 
    i = Strings.InStr(1, Hostname, Environment.NewLine);
    

    另一种方法是使用适当的String.Indexof 函数。

    链接:

    【讨论】:

    猜你喜欢
    • 2017-05-13
    • 2019-10-12
    • 2016-09-09
    • 1970-01-01
    • 2015-08-30
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    相关资源
    最近更新 更多