STRING FUNCTIONS
String s = “COMPUTER”;
C O M P U T E R
0 1 2 3 4 5 6 7
String p = “Applications”;
A p p l i c a t i o n s
0 1 2 3 4 5 6 7 8 9 10 11
Sl No Function Description Data Type Example Output
1 It returns the number of characters of a int s.length( ) 8
length( ) given string
p.length( ) 12
2 It returns a character from a given index char s.charAt(3) P
charAt( )
p.charAt(10) n
3 It returns the index of a given character int s.indexOf(‘M’) 2
indexOf( )
p.indexOf(‘i’) 4
4 lastIndexOf( ) It returns the last index of a given int p.lastIndexOf(‘i’) 8
character
5 toLowerCase( ) It returns the string in lower case letters String s.toLowerCase( ) computer
6 toUpperCase( ) It returns the string in upper case letters String p.toUpperCase( ) APPLICATIONS
7 trim ( ) It removes the spaces from beginning and String “ Java ”.trim( ) Java
end of a string
8 It joins two strings String s.concat(p) or s+p COMPUTERApplications
concat( ) (The + operator can also be used to join
p.concat(s) or p+s ApplicationsCOMPUTER
strings)
9 It checks if a string begins with a given boolean s.startsWith(“COMP”) true
startsWith( ) string or not
p.startsWith(“App”) true
10 It checks if a string ends with a given string boolean s.endsWith(“COMP”) false
endsWith( ) or not
p.endsWith(“cations”) true
11 It replaces one character of a string with String s.replace(‘O’, ‘#’) C#MPUTER
replace( ) another or one substring by another
p.replace(‘a’, ‘@’) Applic@tions
s.replace(“UTER”, “ANY”) COMPANY
12 It checks if two strings are equal or not and boolean s.equals(p) false
equals( ) returns true or false
“JAVA”.equals(“java”) false
equalsIgnoreCase( ) It checks if two strings are equal or not boolean “JAVA”.equalsIgnoreCase true
13 ignoring the case (“java”)
14 It compares the ASCII codes of two strings s.compareTo(p) 2 [C - A = 67 - 65]
and returns the difference of the ASCII code int
p.compareTo(s) ̶ 2 [A – C = 65 – 67]
of the different character
compareTo( ) “bat”.compareTo(“ball”) 8 [t – l = 116-108]
“java”.compareTo(“java”) 0
s.compareTo(“COM”) 5
“COMPUTE”.compareTo(s) ̶ 1 (7-8=-1)
15 It compares the ASCII codes and returns int “JAVA”. compareTo 0
compareToIgnore the difference ignoring the case
IgnoreCase (“java”)
Case( )
“bluej”.compareTo -8
IgnoreCase(“JAVA”)
16 It returns a part of the String based on String p.substring(5) cations
index
s.substring(0) COMPUTER
substring( ) s.substring(0,4) COMP
p.substring(5,8) cat
s.substring(5,10) Runtime error
(StringIndexOutOfBounds)