$show=/label

Guide To Check Char Is In String In Java - indexOf(), lastIndexOf​()

SHARE:

A Quick overview to how to check char or String is in string in java using various methods.

1. Overview

In this tutorial, We will check the possible ways to check the given char or string in the given string. If the char is present then need to return it's index.

Throughout this post, we will be writing the examples on below string.

Check Char Is In String

String string = "find string";


indexof() and lastIndexOf methods return int value as index of the found character.

Please go through the previous post, how String contains() method works in java with examples. This post will give you understanding how indexof method is used internally.

2. indexof()

2.1 indexOf​(int ch)


indexof method is present in java.lang.String package which takes char as method argument and returns int which is the index of the matched chat if found.

Simple words, This method returns the index within this string of the first occurrence of the specified character.

int index = string.indexOf('d');
System.out.println("index for chat d: " + index);

Output:

index for char d: 3

Even though if char 'd' appears multiple time also, it returns first match.

Internally, indexOf method runs the for loop from string index 1 to its length and check every character with the given character by invoking charAt() method.

this.charAt(k) == ch

where k is index from for loop.

If it finds the given char then return its index. If not, returns -1.

int index = string.indexOf('z');

Output:

index for char z: -1

2.2 indexOf​(int ch, int fromIndex)


This method works similar to the above method but it starts search from given fromIndex.

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

index = string.indexOf('i', 4);

Output:

index for char d: 8

Searching char 'i' starts from index 4.

Note: indexof(char c) internally calls indexOf​(int ch, int fromIndex) method as indexOf​(ch, 0).

3. lastIndexOf​

3.1 lastIndexOf​(int ch)


lastIndexOf​ method searches the char from index 0 to length-1. But this returns the last match and returns it's index. This method also internally uses charAt method.

this.charAt(k) == ch

In input string "find string", char 'i' is present two times at index 1 and 8. Now, we'll call lastIndexOf​ method and output should the 8 for char 'i'. See the below code.

index = string.lastIndexOf('i');
System.out.println("last index for char i: " + index);

Output:

last index for char i: 8

If no char finds then returns '-1'.

This method works internally search backwards starting index from length-1 to zero.

3.2 lastIndexOf​(int ch, int fromIndex)


This method returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

Internal condition:

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

Now, we will pass fromIndex as '3' then it will start searching backward from index 3 to 0.

index = string.lastIndexOf('i', 3); 
System.out.println("last index for char i: " + index);

Output:

last index for char i: 1

4 indexOf​(String str)


We'll use the below string in examples from this point.

String newString = "hello java, welcome to java w3schools blog";

4.1 indexOf​(String str)

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

index = newString.indexOf("java");
System.out.println("string \"java\" index found at: " + index);

Output:

string "java" index found at: 6


Internally, this method calls this.startsWith(str, k) method.

4.2 indexOf​(String str, int fromIndex)

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

index = newString.indexOf("java", 9);
System.out.println("string \"str\" index found at: " + index);

Output:

string "java" index found at: 23

In the above example, seaching will start from index 9. It ignores the match at index 5 and take match from index 23.

Internally, this method calls below code.

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

4.3 lastIndexOf​(String str)


Returns the index within this string of the last occurrence of the specified substring. The last occurrence of the empty string "" is considered to occur at the index value this.length().

index = newString.lastIndexOf("java");
System.out.println("string \"str\" index found at: " + index);

Output: 

lastIndexOf: string "str" index found at: 23

4.4 lastIndexOf​(String str, int fromIndex)


Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

index = newString.lastIndexOf("java", 9);
System.out.println("lastIndexOf: string \"str\" index found at: " + index); 

Output:

lastIndexOf: string "str" index found at: 6

5. Conclusion

In this article, we've seen how to find the char is present in the string using string api methods such as indexOf, lastIndexOf methods.
Finally, if index is negetive then it will return value '-1'.
indexOf method is used internally in contains(), replace(), split(), isBlank(), indent() methods.


All examples shown in this post are available on GitHub.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Guide To Check Char Is In String In Java - indexOf(), lastIndexOf​()
Guide To Check Char Is In String In Java - indexOf(), lastIndexOf​()
A Quick overview to how to check char or String is in string in java using various methods.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzwcdE-ZKLJA1P4iD5PXsXzabVulyG9uickul3JLmNmFl9BMApFPCWRhpy_p8tT7lUv0sAPVqYoGSJFqtRLTq9lLPBPGJYbuCtqR34AIbgGTST2vmGX_NySQObplK2apP5YwJ-UXkWfUQ/s400/Check+Char+Is+In+String.PNG
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzwcdE-ZKLJA1P4iD5PXsXzabVulyG9uickul3JLmNmFl9BMApFPCWRhpy_p8tT7lUv0sAPVqYoGSJFqtRLTq9lLPBPGJYbuCtqR34AIbgGTST2vmGX_NySQObplK2apP5YwJ-UXkWfUQ/s72-c/Check+Char+Is+In+String.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/05/check-char-in-string.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/05/check-char-in-string.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content