Java indexOf 为未找到的字符串返回false?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/696809/
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-11 18:27:17  来源:igfitidea点击:

Java indexOf returns false for unfound string?

java

提问by Supernovah

I need to know whether in Java does the indexOf()method return falseor voidfor an unfound string? or does it return an index intof 0?

我需要知道在 Java 中该indexOf()方法是返回false还是返回void未找到的字符串?还是返回索引int为 0?

回答by Brian Agnew

It'll return -1 (hint: try it)

它会返回 -1(提示:试试看)

As in the JavaDoc

就像在JavaDoc 中一样

回答by Thomas Owens

The Java API docscontain this answer. the indexOfmethods on a Stringreturn -1 if the character is not found.

Java的API文档包含这个答案。如果未找到字符,则返回 -1的indexOf方法String

回答by Gustavo

You mean Javascript? It returns -1.

你的意思是Javascript?它返回-1。

回答by Brian Rasmussen

Look at the signature. It says int, so an integer is returned. To return another type (void or boolean) the signature would be different.

签名。它说int,所以返回一个整数。要返回另一种类型(void 或 boolean),签名会有所不同。

回答by scunliffe

Only PHP's str_posis weird enough to return 0/false when the index isn't found. Most consider the PHP version to be a bad implementation.

只有PHP 的 str_pos很奇怪,当找不到索引时返回 0/false 。大多数人认为 PHP 版本是一个糟糕的实现。

int strpos  ( string $haystack  , mixed $needle  [, int $offset= 0  ] )

//Returns the position as an integer. If needle  is not found, strpos()
// will return boolean  FALSE.

/*
  Warning
  function may return Boolean FALSE, but may also return a non-Boolean value which
  evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more
  information. Use the === operator for testing the return value of this function.
*/