C# 替代使用 InStr

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19441217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:59:36  来源:igfitidea点击:

Alternative to using InStr

c#vb.net

提问by XK8ER

how can I use a different function "InStr" this is the code that I am using and works fine but moving away from InStr is my goal

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

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

采纳答案by ??ssa P?ngj?rdenlarp

String.Indexof()with several overloads:

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)

There is also a String,LastIndexOf()method to get the last occurance of something in a string also with a variety of overloads.

还有一种String,LastIndexOf()方法可以使用各种重载来获取字符串中某事物的最后一次出现。

Available in MSDNor Object Browser (VIEW menu | Object Browser) in the VS near you.

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

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

回答by Alezis

If you need equivalent C# code you can use Stringsclass from Microsoft.VisualBasicassembly, thus code can be like following:

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

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

enter image description here

在此处输入图片说明

Another approach is using appropriate String.Indexoffunction.

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

Links:

链接: