Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to using InStr

Tags:

c#

.net

vb.net

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

i = InStr(1, Hostname, Environment.Newline)
like image 837
XK8ER Avatar asked Oct 18 '13 03:10

XK8ER


People also ask

What is equivalent of InStr in C#?

You can use string. IndexOf(string) to do the same thing.

What is the value returned by InStr ()?

Returns a Variant (Long) specifying the position of the first occurrence of one string within another. Optional. Numeric expression that sets the starting position for each search.

What is InStr in vb6?

InStr(Int32, String, String, CompareMethod) Returns an integer specifying the start position of the first occurrence of one string within another. InStr(String, String, CompareMethod) Returns an integer specifying the start position of the first occurrence of one string within another.


2 Answers

String.Indexof() with several overloads:

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.

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

i = Hostname.Indexof(Environment.Newline, 1)
like image 70
Ňɏssa Pøngjǣrdenlarp Avatar answered Oct 31 '22 21:10

Ňɏssa Pøngjǣrdenlarp


If you need equivalent C# code you can use Strings class from Microsoft.VisualBasic assembly, thus code can be like following:

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

enter image description here

Another approach is using appropriate String.Indexof function.

Links:

  • http://msdn.microsoft.com/en-us/library/8460tsh1.aspx
  • http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.aspx
  • http://msdn.microsoft.com/en-us/library/k8b1470s.aspx
like image 8
Alezis Avatar answered Oct 31 '22 22:10

Alezis