Java string: indexof() method

Yazım

arr.indexOf(aranacakEleman)
arr.indexOf(aranacakEleman, aramayaBaşlanacakİndex)

Parametreler

aranacakEleman
Array içerisinde aranacak elemanı karşılayacak metod parametresidir.
aramayaBaşlanacakİndexOptional
Aramaya başlanacak index değerini karşılayacak metod parametresidir. Eğer index olarak gönderilmiş argümanın değeri array’in uzunluğuna eşit veya daha büyükse, metod -1 değerini döndürür, bu array’in hiç aranmayacağı anlamına gelmektedir. Eğer argümanın değeri negatif bir değerse bu durumda argüman değeri array’in sonundan offset olarak algılanacaktır. Not: eğer index argümanı negatif ise, array hala baştan sona aranacaktır. Bu durumda elemanın bulunduğu index negatif hesaplanırsa, bütün array baştan aranacaktır. Default: 0 (tüm array baştan aranacaktır).

Java indexOf Method syntax

The Java Programming Language provides four different methods to return the index position.


The following method will accept the character as the parameter and return the index position of the first occurrence of the specified character.

It will accept the character as the first parameter and Starting index position (Starting_index) as the second argument. Java String.indexOf method will start looking from the Starting_index and return the index position of the first occurrence of the specified character.

The following Java indexof method will accept the string data as the argument and return the index position of the first occurrence of the specified substring.

It will accept the string data as the first parameter and Starting index position (Starting_index) as the second argument. Java String.indexOf method will start looking from the Starting_index and return the index position of the first occurrence of the specified substring.

  • String_Object: Please specify the valid String Object.
  • Starting_Index: Please specify the starting index position. If you specify this value then, instead of looking from index position 0 String.indexOf function will start looking from this position.

NOTE: If you specify the negative value as the Starting_Index then, Java String.indexOf function will start looking from index 0.

Java indexOf Method Example

The Java string indexOf method returns the index position of the first occurrence of a specified string. This Java program will help to understand the Java string.indexOf method.

OUTPUT

ANALYSIS

Within this Java string indexOf Method example, we declared two String variables Str1, Str2, and assigned corresponding values using the following statement.

It will call the public int indexOf (int ch) method to find the index position of ‘a’

The following string indexof statement will call the public int indexOf (int ch, int Starting_Index) method to find the index position of ‘a’ starting at index position 10.

Next we used the negative value as the Starting_Index. Java string Indexof function will start looking for a’ starting at index position 0.

In the next line, we are looking for the non-existing item ‘z’ inside the str. It will call the public int indexOf (int ch) method to find the index position of ‘z’ since it does not find, it is returning -1 as output.

This Java indexof statement calls the public int indexOf (String str) method to find the index position of a substring ‘abc’ and store the index value in variable e.

NOTE: You should count the space as One Character.

From the above statement, although term abc repeated multiple times, the Java string Indexof function is returning the index of a first occurrence.

Now, let us provide the starting index position for the indexof. The following statement will call the public int indexOf (String str, int Starting_Index) method to return the first occurrence of string abc starting at index position 9.

In the next line, we specified the starting index point at 25, and we all know that there is no substring “abc” after the index position 25. So, Indexof String Method is returning -1.

Синтаксис

arr.includes(valueToFind)

Параметри

Значення елемента, який слід знайти.

Примітка: При порівнянні рядків та літер,  чутливий до регістру.

fromIndex Optional
Позиція у масиві, з якої потрібно починати пошук ; перша літера шукатиметься за індексом , якщо  є позитивним значенням, або за індексом , якщо  від’ємний (використовуючи абсолютну величину  як кількість літер з кінця масиву, де потрібно починати пошук). За замовчуванням дорівнює 0.

Вертає

Значення , яке дорівнює , якщо значення знайдене у масиві (або у частині масиву, якщо заданий параметр ). Всі нульові значення вважаються рівними, незалежно від знаку (тому -0 вважатиметься рівним і 0, і +0), але не вважається тим самим, що й 0.

Примітка: Технічно кажучи,  використовує алгоритм  для визначення того, чи знайдено заданий елемент.

indexOf() Method

Contents:

public int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character. If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned. For values of ch in the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:

this.charAt(k) == ch

is true. For other values of ch, it is the smallest value k such that:

this.codePointAt(k) == ch

is true. In either case, if no such character occurs in this string, then -1 is returned.

Java Platform: Java SE 8

Syntax:

indexOf(int ch)

Parameters:

Name Description Type
ch a character (Unicode code point). int

Return Value : the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

Return Value Type: int

Pictorial presentation of Java String indexOf() Method

Example: Java String indexOf() Method

The following example shows the usage of java String() method.

Output:

 a  b c  d e  f  g h i  j                              
=========================                              
36 10 7 40 2 16 42 1 6 20                              
                                                       
k  l  m  n  o  p q  r  s  t                            
===========================                            
8 35 22 14 12 23 4 11 24 31                            
                                                       
u  v  w  x  y  z                                       
================                                       
5 27 13 18 38 37 

public int indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

If a character with value ch occurs in the character sequence represented by this String object at an index no smaller than fromIndex, then the index of the first such occurrence is returned. For values of ch in the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:

(this.charAt(k) == ch) && (k >= fromIndex)

is true. For other values of ch, it is the smallest value k such that:


is true. For other values of ch, it is the smallest value k such that:

(this.codePointAt(k) == ch) && (k >= fromIndex)

is true. In either case, if no such character occurs in this string at or after position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is negative, it has the same effect as if it were zero: this entire string may be searched. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: -1 is returned.

All indices are specified in char values (Unicode code units).

Java Platform: Java SE 8

Syntax:

indexOf(int ch, int fromIndex)

Parameters:

Name Description Type
ch a character (Unicode code point). int
fromIndex the index to start the search from. int

Return Value: the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur.

Return Value Type: int

Example: Java String indexOf(int ch, int fromIndex) Method

The following example shows the usage of java String() method.

Output:

the quick brown fox jumps over the lazy dog.           
indexOf(t, 60) = 31

public int indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.

The returned index is the smallest value k for which:

this.startsWith(str, k)

If no such value of k exists, then -1 is returned.

Java Platform: Java SE 8

Syntax:

indexOf(String str)

Parameters:

Name Description Type
str the substring to search for. int

Return Value: the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.


Return Value Type: int

Example: Java String indexOf(String, str) Method

The following example shows the usage of java String() method.

Output:

This is an example of indexOf from w3resource.com      
indexOf(w3r) = 35

public int indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

The returned index is the smallest value k for which:

k >= fromIndex && this.startsWith(str, k)

If no such value of k exists, then -1 is returned.

Java Platform: Java SE 8

Syntax:

indexOf(String str, int fromIndex)

Parameters:

Name Description Type
str the substring to search for. int
fromIndex the index from which to start the search. int

Return Value: the index of the first occurrence of the specified substring, starting at the specified index, or -1 if there is no such occurrence.

Return Value Type: int

Example: Java String indexOf(String str, int fromIndex) Method

The following example shows the usage of java String() method.

Output:

the quick brown fox jumps over the lazy dog.           
indexOf(the, 40) = 31

Java Code Editor:

Previous:hashCode MethodNext:intern Method

Polyfill

// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let o be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var o = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of o with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = o.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = fromIndex | 0;

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of o with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of o with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in o && o === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}

示例

使用indexOf

以下例子使用

var array = ;
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

找出指定元素出现的所有位置

var indices = [];
var array = ;
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// 

判断一个元素是否在数组里,不在则更新数组

function updateVegetablesCollection (veggies, veggie) {
    if (veggies.indexOf(veggie) === -1) {
        veggies.push(veggie);
        console.log('New veggies collection is : ' + veggies);
    } else if (veggies.indexOf(veggie) > -1) {
        console.log(veggie + ' already exists in the veggies collection.');
    }
}

var veggies = ;

// New veggies collection is : potato,tomato,chillies,green-papper,spinach
updateVegetablesCollection(veggies, 'spinach'); 
// spinach already exists in the veggies collection.
updateVegetablesCollection(veggies, 'spinach'); 

Polyfill

在ECMA-262 标准 的第5版中被加入,但并非所有的浏览器都支持该方法。你可以在编写scripts时,在其开头使用以下代码,它能够允许你在没有本地支持的情况下使用indexOf方法。该算法符合ECMA-262第5版其中一项规定, 即假定 和 呈现它们原有的值。

// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let O be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of O with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in O && O === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}

Підтримка веб-переглядачами

Таблиця сумісності на цій сторінці створена зі структурованих даних. Якщо ви хочете долучитися до розробки цих даних, пропонуйте нам свої pull request до репозиторію https://github.com/mdn/browser-compat-data.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 3 Opera Full support 3 Safari Full support 1 WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support 10.1 Safari iOS Full support 1 Samsung Internet Android Full support 1.0 nodejs Full support 0.1.100

С этим читают