Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOf method returns 0 when it should had return -1 in C# / Java

A friend of mine came to me with this strange behavior which i can't explain, any insight view would be appreciated.

Im running VS 2005 (C# 2.0), the following code show the behavior

int rr = "test".IndexOf("");
Console.WriteLine(rr.ToString());

the above code, print "0" which clearly show it should have return -1

This also happen in Java where the following Class show the behavior:

public class Test{
 public static void main(String[] args){
   System.out.println("Result->"+("test".indexOf("")));
 }
}

Im running Java 1.6.0_17

like image 531
jcgarciam Avatar asked Apr 02 '10 19:04

jcgarciam


2 Answers

Quote from the C# documentation:

If value is Empty, the return value is 0.

The behavior that you describe is entirely as expected (at least in C#).

like image 81
Fredrik Mörk Avatar answered Oct 25 '22 12:10

Fredrik Mörk


0 is correct. Start at position zero and you can (trivially) match a zero-length string. Likewise, "" contains "".

like image 34
Marc Gravell Avatar answered Oct 25 '22 14:10

Marc Gravell