Reputation: 117
I am not sure why I get the result of 0
, which is the correct value of a
I have in VB
Dim searched As String = "<results>" & vbCrLf & "<field name=\""FID\""/>" & vbCrLf & "<field name=\""StartFID\""/>" & vbCrLf & "<field name=\""Vertex1\""/>" & vbCrLf & "<field name=\""Vertex2\""/>" & vbCrLf & "<field name=\""Slope\""/>" & vbCrLf & ""
Dim sought As String = "<rs FID=\""87\"" StartFID=\""87\"" Vertex1=\""29\"" Vertex2=\""30\"" Slope=\""-1\""/>"
Dim a As Integer = InStr(searched, sought)
What I would like to do, is get the same result of a == 0
when converted to c#.
I have tried
int a = String.Compare(searched, sought);
int a = String.IndexOf(searched, sought);
int a = String.Equals(searched, sought);
Upvotes: 2
Views: 41525
Reputation: 597
Simply You can use IndexOf()+1 to return 0 instead of -1
int a = searched.IndexOf(sought)+1;
it work for me hop it help
Upvotes: 4
Reputation: 117
Works... Thanks Carsten
int b = searched.IndexOf(sought);
b = 0
I see the problem I had now... when I move the string to a variable that calculates the string I get the error. I wasn't sure whether I had the correct use of InStr.
Upvotes: 0
Reputation: 726599
One difference between InStr
and IndexOf
's behavior is that InStr
returns zero when the string is not found, while IndexOf
returns -1. Using IndexOf
is the idiomatic way of searching for substrings in C#, and the correct method to use in your situation.
If you would like to use InStr
directly, you could do it by referencing Microsoft.VisualBasic
assembly, and then calling InStr
as a static method of the Strings
class:
int a = Strings.InStr(searched, sought);
Upvotes: 4
Reputation: 2806
The three methods are all for different purposes and do not the same. That is why they have different names..
int a = String.IndexOf(searched, sought);
This is the method that you should use and is exactly for that purpose.
Alternatively you could use string.Contains()
.
int a = String.Compare(searched, sought);
Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.
bool a = String.Equals(searched, sought);
Determindes equality of two strings.
Upvotes: 0
Reputation: 151594
Strings in C# are zero-indexed. If a.IndexOf(b)
returns 0
, then string b
is present in string a
at position 0
.
If the sought string is not in the input, IndexOf()
returns -1
.
Upvotes: 5
Reputation: 553
String.IndexOf
should work, but if you truly want to use InStr, you can still do it. Just add a reference to Microsoft.VisualBasic.dll, and a "using Microsoft.VisualBasic;" at the top of your file, and you can use Strings.InStr
:
Like Strings.InStr(searched, sought)
Upvotes: 0