IndexOf方法返回0,当它应该有返回-1在C#/ Java的 [英] IndexOf method returns 0 when it should had return -1 in C# / Java

查看:524
本文介绍了IndexOf方法返回0,当它应该有返回-1在C#/ Java的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个朋友来找我有这种奇怪的行为,我无法解释,任何有识之士认为,将不胜感激。



进出口运行VS 2005(C#2.0 ),下面的代码显示的行为

  INT RR =测试.IndexOf(); 
Console.WriteLine(rr.ToString());



上面的代码,打印0,这清楚地表明它应该有返回-1



这也发生在Java中,其中以下级显示的行为:

 公共类测试{
公共静态无效的主要(字串[] args){
的System.out.println(Result->+(测试.indexOf()));
}
}



进出口运行的Java 1.6.0_17


解决方案

这是不是一个例外,而是一个自然的结果如何的indexOf startsWith 定义。



您所声称测试.indexOf( )应该返回 1 。这基本上等同于宣称测试.startsWith()应该返回。为什么是这样?虽然这种情况在文档中具体阐述为返回真正,这不只是一个武断的决定。



如何你将决定测试.startsWith(TE),例如?最简单的方法是使用递归。由于两个字符串开头的字符'T',你叫EST.startsWith(E)和返回结果。同样的,你会调用ST.startsWith()并返回结果。不过你已经知道,为什么每个字符串真正,所以这是p>

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

解决方案

This is not an exception to the rule, but rather a natural consequence of how indexOf and startsWith are defined.

You’re claiming that "test".indexOf("") should return -1. This is essentially equivalent to the claim that "test".startsWith("") should return false. Why is this? Although this case is specifically addressed in the documentation as returning true, this is not just an arbitrary decision.

How would you decide "test".startsWith("te"), for example? The simplest way is to use recursion. Since both strings start with the character 't', you call "est".startsWith("e") and return the result. Similarly, you will call "st".startsWith("") and return the result. But you already know that the answer should be true, so that is why every string starts with "".

这篇关于IndexOf方法返回0,当它应该有返回-1在C#/ Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆