java string indexof method with code examples
이 튜토리얼에서는 문자 또는 문자열의 색인을 찾기 위해 Java String indexOf () 메소드와 구문 및 프로그래밍 예제에 대해 학습합니다.
Java indexOf () 메서드와 관련된 다른 옵션과 간단한 프로그래밍 예제와 함께 사용법을 살펴 보겠습니다.
이 튜토리얼을 진행하면 다양한 형태의 String indexOf () Java 메소드를 이해할 수 있으며 자신의 프로그램에서 사용하는 데 익숙해 질 것입니다.
학습 내용 :
Java String indexOf 메서드
이름에서 알 수 있듯이 Java String indexOf () 메서드는 자리 값이나 인덱스 또는 주어진 문자 나 문자열의 위치를 반환하는 데 사용됩니다.
Java indexOf ()의 리턴 유형은 다음과 같습니다. '정수' .
통사론
구문은 다음과 같이 제공됩니다. int indexOf (문자열 str) 여기서 str은 String 변수이고 str의 첫 번째 발생 인덱스를 반환합니다.
옵션
Java indexOf () 메소드를 사용하는 데는 기본적으로 네 가지 옵션 / 변형이 있습니다.
- int indexOf (문자열 str)
- int indexOf (문자열 str, int StartingIndex)
- int indexOf (int char)
- int indexOf (int char, int StartingIndex)
앞에서 설명한 것처럼 Java indexOf () 메서드는 문자열 또는 문자열의 문자 중 하나의 자리 값을 반환하는 데 사용됩니다. indexOf () 메서드에는 문자뿐만 아니라 문자열에 대해 각각 두 가지 옵션이 있습니다.
우리는 이미 StartingIndex와 함께 등장하는 문자열과 문자의 첫 번째 변형과 두 번째 변형에 대해 논의했습니다. 이 시작 색인은 문자 색인에 대한 검색을 시작해야하는 색인입니다.
부분 문자열의 인덱스 찾기
이것은 Java indexOf () 메소드의 가장 간단한 형식입니다. 이 예에서 기본 문자열의 일부인 부분 문자열의 인덱스를 찾을 입력 문자열을 가져옵니다.
public class indexOf { public static void main(String() args) { String str = 'Welcome to Softwaretestinghelp'; //Printing the index of a substring 'to' System.out.println(str.indexOf('to')); } }
산출:
문자 인덱스 찾기
이 예에서 , 우리는 메인 문자열에서 문자의 인덱스를 찾으려고 할 때 StartingIndex가 어떻게 작동하는지 볼 것입니다. 여기에서 두 개의 다른 StartingIndex를 지정하고 차이점도 확인하는 입력 문자열을 가져 왔습니다.
첫 번째 print 문은 0 번째 인덱스에서 검색 할 때 1을 반환하고 두 번째 print 문은 5 번째 인덱스에서 검색 할 때 6을 반환합니다.
public class indexOf { public static void main(String() args) { String str = 'Welcome'; //returns 1 as it is searching from the 0th index System.out.println(str.indexOf('e', 0)); //returns 6 as it is searching from the 5th index. System.out.println(str.indexOf('e', 5)); } }
산출:
시나리오
시나리오 1 : 메인 문자열에서 사용할 수없는 문자의 인덱스를 찾으려고하면 어떻게됩니까?
설명: 여기서는 String 변수를 초기화했으며 메인 String에서 사용할 수없는 하위 문자열뿐만 아니라 문자의 인덱스를 가져 오려고합니다.
이러한 유형의 시나리오에서 indexOf () 메서드는 항상 -1을 반환합니다.
public class indexOf { public static void main(String() args) { String str = 'Software Testing'; /* * When we try to find the index of a character or String * which is not available in the Main String, then * it will always return -1. */ System.out.println(str.indexOf('X')); System.out.println(str.indexOf('x')); System.out.println(str.indexOf('y')); System.out.println(str.indexOf('z')); System.out.println(str.indexOf('abc')); } }
산출:
시나리오 2 : 이 시나리오에서는 주어진 문자열에서 문자 또는 부분 문자열의 마지막 발생을 찾으려고합니다.
설명: 여기서는 Java indexOf () 메소드의 추가 메소드에 익숙해 질 것입니다. 그만큼 lastIndexOf () 메서드 문자 또는 하위 문자열의 마지막 발생을 찾는 데 사용됩니다.
이 예에서 문자 'a'의 마지막 색인을 가져옵니다. 이는 Java indexOf () 메소드와 lastIndexOf () 메소드로 수행 할 수 있습니다.
lastIndexOf () 메서드는 StartingIndex를 전달할 필요가 없기 때문에 이러한 종류의 시나리오에서 사용하기 쉽습니다. indexOf () 메서드를 사용하는 동안 인덱스가 시작되는 위치에서 StartingIndex를 8로 전달하고 'a'항목을 계속 찾을 수 있습니다.
public class indexOf { public static void main(String() args) { String str = 'Saket Saurav'; /* * The first print statement is giving you the index of first * occurrence of character 'a'. The second and third print * statement is giving you the last occurrence of 'a' */ System.out.println(str.indexOf('a')); System.out.println(str.lastIndexOf('a')); System.out.println(str.indexOf('a', 8)); } }
산출:
자주 묻는 질문
Q # 1) 길이 방법을 사용하지 않고 Java에서 문자열 길이를 찾는 방법은 무엇입니까?
대답: Java에는 String의 길이를 찾는 데 사용되는 length ()라는 내장 메소드가 있습니다. 이것은 길이를 찾는 표준 방법입니다. 그러나 lastIndexOf () 메서드를 사용하여 String의 길이를 찾을 수도 있지만 콘솔을 통해 입력을 제공하는 동안에는 사용할 수 없습니다.
두 가지 방법을 모두 사용하여 문자열의 길이를 찾은 아래 예제를 보겠습니다.
public class indexOf { public static void main(String() args) { String str = 'Software Testing Help'; /* Here we have used both length() and lastIndexOf() method * to find the length of the String. */ int length = str.length(); int length2 = str.lastIndexOf('p'); length2 = length2 + 1; // Printing the Length using length() method System.out.println('Length using length() method = ' + length); // Printing the Length using lastIndexOf() method System.out.println('Length using lastIndexOf() method = ' + length2); } }
산출:
Q # 2) Java에서 점의 색인을 찾는 방법은 무엇입니까?
대답: 아래 프로그램에서 문자열의 일부인‘.’의 색인을 찾을 수 있습니다. 여기서는 두 개의 '.'가 포함 된 입력 문자열을 가져 와서 indexOf () 및 lastIndexOf () 메서드를 사용하여 첫 번째 및 마지막 점 '.'의 자릿값을 찾습니다.
public class indexOf { public static void main(String() args) { String str = 'saket.saurav8@abc.com'; /* Here, we are going to take an input String which contains two ‘.’ * and then with the help of indexOf() and lastIndexOf() methods, * we will find the place value of first and the last dot '.' */ System.out.println(str.indexOf('.')); System.out.println(str.lastIndexOf('.')); } }
산출:
Q # 3) Java에서 배열 요소의 값을 얻는 방법은 무엇입니까?
대답:
다음은 배열의 요소를 추출하는 프로그래밍 예제입니다.
요소는 arr (0)에서 시작하므로 마지막 색인까지 arr (0)…을 인쇄 할 때 주어진 색인에 지정된 요소를 검색 할 수 있습니다. 이는 요소의 인덱스 번호를 지정하거나 루프를 사용하여 수행 할 수 있습니다.
public class indexOf { public static void main(String() args) { String arr() = {'Software', 'Testing', 'Help'}; /* Elements start from arr(0), hence when we * print arr(0)... till the last index, we will * be able to retrieve the elements specified at a * given index. This is also accomplished by using For Loop */ System.out.println(arr(0)); System.out.println(arr(1)); System.out.println(arr(2)); System.out.println(); System.out.println('Using For Loop: '); for (int i=0; i 산출:

Q # 4) Java에서 목록의 색인을 얻는 방법은 무엇입니까?
대답: 아래 프로그램에서 몇 가지 요소를 추가 한 다음 목록에있는 요소의 색인을 찾으려고했습니다.
import java.util.LinkedList; import java.util.List; public class indexOf { public static void main(String() args) { /* Added a few elements in the list and then * found the index of any of the elements */ List list = new LinkedList(); list.add(523); list.add(485); list.add(567); list.add(999); list.add(1024); System.out.println(list); System.out.println(list.indexOf(999)); } }
산출:

Q # 5) Java에서 문자열의 두 번째 마지막 인덱스를 얻는 방법은 무엇입니까?
대답: 여기에서 두 번째 마지막 인덱스와 문자열에서 발생하는 두 번째 마지막 문자를 찾았습니다.
두 번째 마지막 문자를 찾아야하므로 문자열 길이에서 2자를 뺍니다. 문자를 찾으면 chars (i)와 두 번째 마지막 문자의 인덱스를 사용하여 인쇄했습니다.
public class indexOf { public static void main(String() args) { String str = 'Software Testing Help'; char() chars = str.toCharArray(); /* Since, we have to find the second last character, we have subtracted 2 characters * from the length of the String. Once the character is found, we have printed * using chars(i) and also the index of the second last character. */ for(int i=chars.length-2; i>0;) { System.out.println('The second last character is ' + chars(i)); System.out.println('The index of the character is ' + str.indexOf(chars(i))); break; } } }
산출:

결론
이 튜토리얼에서는 Java indexOf () 메소드와 관련된 옵션과 함께 Java String indexOf () 메소드를 자세히 이해했습니다.
1에서 10 사이의 C ++ 난수
더 나은 이해를 위해이 튜토리얼은 indexOf () 및 lastIndexOf () 메서드를 사용하는 방법을 설명하기 위해 각 사용에 대한 적절한 프로그래밍 예제와 함께 다양한 시나리오 및 FAQ의 도움으로 설명되었습니다.
추천 도서