indexOf() ,length() and trim()
Let us understand IndexOf(), length() and trim()
indexOf() method
This method returns the index of first
occurrence of a substring or a character or -1
if the character does not occur.
indexOf() method has 4 different overloaded forms
int indexOf(int ch)
It returns the index of the first occurrence of the specified character within this string
int indexOf(String str)
It returns the index of the first occurrence of the specified substring within this string
int indexOf(int ch, int fromIndex)
It returns the index of the first occurrence of the specified character, starting the search at the specified index within this string.
int indexOf(String str, int fromIndex)
It returns the index of the first occurrence of the specified substring, starting at the specified index within this string.
Example
- public class StringIndexOfExample {
- public static void main(String[] args) {
- String str="javainsimpleway";
- System.out.println(str.indexOf('a'));
- System.out.println(str.indexOf('i', 5));
- String subString="simple";
- System.out.println(str.indexOf(subString));
- System.out.println(str.indexOf(subString,8));
- }
- }
public class StringIndexOfExample { public static void main(String[] args) { String str="javainsimpleway"; System.out.println(str.indexOf('a')); System.out.println(str.indexOf('i', 5)); String subString="simple"; System.out.println(str.indexOf(subString)); System.out.println(str.indexOf(subString,8)); } }
length()
method
This method returns the number of characters in the given string
Example :
- String str=”java in simple way”;
- System.out.println(str.length());
String str=”java in simple way”; System.out.println(str.length());
Note :
Space is also a character and hence above output is 16 including space
trim()
method
This method returns a string by removing any leading and trailing whitespaces.
Method signature
- public String trim()
public String trim()
Example :
- public class StringTrimExample1{
- public static void main(String args[]){
- String str=" java ";
- System.out.println(str.trim());
- }
- }
public class StringTrimExample1{ public static void main(String args[]){ String str=" java "; System.out.println(str.trim()); } }
If the whitespaces are between the string, trim() method will not remove
such whitespaces, it will remove
whitespace at the beginning and end of string
Example
- public class StringTrimExample2{
- public static void main(String args[]){
- String str=" java in simple way ";
- System.out.println(str.trim());
- }
- }
public class StringTrimExample2{ public static void main(String args[]){ String str=" java in simple way "; System.out.println(str.trim()); } }