Complete String Methods
Complete String Methods
In Java, a string is an object that represents a number of character values. Each letter
in the string is a separate character value that makes up the Java string object.
Characters in Java are represented by the char class. Users can write an array of char
values that will mean the same thing as a string.
Page 1 of 30
Syntax:
public String trim()
The method accepts no parameters.
Returns:
It returns the omitted string with no leading and trailing spaces.
class Gfg {
// driver code
public static void main(String args[])
{
System.out.println("\nCharacter at Index");
System.out.println("At 0 the character is" + name.charAt(0));
System.out.println("At 3 the character is" + name.charAt(3));
}}
Page 4 of 30
int indexOf(char ch) and int lastIndexOf(char ch)
indexof( ): Returns the index within the current string object of the first occurrence
of the specified character*/
int indexOf(char ch)
The method indexOf() is used for finding out the index of the specified character
or substring in a particular String. There are 4 variations of this method:
int indexOf(int ch): It returns the index of the first occurrence of character ch in a
String.
int indexOf(int ch, int fromIndex): It returns the index of first occurrence if
character ch, starting from the specified index “fromIndex”.
int indexOf(String str): Returns the index of string str in a particular String. int
indexOf(String str, int fromIndex): Returns the index of string str, starting from the
specified index “fromIndex”.
public class IndexOfExample{
public static void main(String args[]) {
String str1 = new String("This is a BeginnersBook tutorial");
String str2 = new String("Beginners");
String str3 = new String("Book");
String str4 = new String("Books");
System.out.println("Index of B in str1: "+str1.indexOf('B'));
System.out.println("Index of B in str1 after 15th char:"+str1.indexOf('B', 15));
System.out.println("Index of B in str1 after 30th char:"+str1.indexOf('B', 30));
System.out.println("Index of string str2 in str1:"+str1.indexOf(str2));
System.out.println("Index of str2 after 15th char"+str1.indexOf(str2, 15));
System.out.println("Index of string str3:"+str1.indexOf(str3));
System.out.println("Index of string str4"+str1.indexOf(str4));
System.out.println("Index of harcoded string:"+str1.indexOf("is"));
System.out.println("Index of hardcoded string after 4th
char:"+str1.indexOf("is", 4));
}
}
Page 5 of 30
/* lastIndexOf( ): Example method illustrating use of lastIndexOf
method*/
The java string lastIndexOf() method returns last index of the given
character value or substring. If it is not found, it returns -1. The index counter
starts from zero.
Internal Implementation
public int lastIndexOf(int ch) {
return lastIndexOf(ch, value.length - 1);
}
2 int lastIndexOf(int ch, int returns last index position for the
fromIndex) given char value and from index
Parameters
fromIndex: index position from where index of the char value or substring is
Page 6 of 30
returned
Returns
System.out.println(index1);//6
}}
// Method 1
{
String name1="NPS";
String name2="International";
name1 = name1.concat(name2);
System.out.println(name1);
Page 8 of 30
// Method 2 using + operator
String name3="Bluej";
String name4="Java";
name3= name3 + " " +name4;
System.out.println(name3);
}
}
/* #4 Equals
boolean equals(String str) – Compares the current string object to the specified
string object str .
equals method returns a boolean value. (either true or false)
Page 9 of 30
/* Equals Ignore Case
boolean equalsIgnoreCase(String str) : Compares the current string object to
str, ignoring case considerations.
//import java.lang.*;
// even if ignoring the cases both the strings are not equal.
boolean result2 = str2.equalsIgnoreCase(str3);
System.out.println("str2 is equal to str3 = " + result2);
}
}
Page 10 of 30
ASCII – American Standard Code for Information Interchange
Page 11 of 30
compareTo()
Definition:
It is used to compare 2 strings lexicographically.
compareTo( ) – the return type is integer
A – Z => 65 – 90
a – z => 97 – 122
a-A = 97-65 = 32
A-a = 65-97 = -32
Page 12 of 30
Calculating the returned value when both strings are of the
same case:
EXAMPLE 1:
String s1=”Apple”;
String s2=”Human”;
s1.compareTo(s2);
[s1 - s2]
Steps:
- Write down the ASCII value of s1 => (65)
- Write down the ASCII value of s2 => (72)
- Now subtract both.
- 65 - 72 = -7.
EXAMPLE 2:
String s1=”DEDICATE”;
String s2=”DEVOTE”;
s2.compareTo(s1);
[s2 - s1]
Steps:
- In this example, the letters differ only in the 3rd position.
- So, compare s1’s value (D) to s2’s value (V)
- Write down the ASCII value of s2 => (86)
- Write down the ACSII value of s1 => (68)
- Now subtract both.
- 86– 68= +18.
Page 13 of 30
Calculating the returned value when both strings are of
different cases:
WHY?
While comparing from Upper case to
Consider A – a Lower case, ADD 32.
A.compareTo(a);
While comparing from Lower case to
65 – 97 = -32 Upper case, SUBTRACT 32.
Consider a – A
a.compareTo(A);
97 – 65 = 32
EXAMPLE 1:
String s1=”DEDICATE”;
String s2=”devote”;
s2.compareTo(s1);
[s2 - s1]
Answer = 32
EXAMPLE 2:
String s1=”Apple”;
String s2=”human”;
s1.compareTo(s2);
[s1 - s2]
Steps:
- Write down the ASCII value of s2 => (104)
- Write down the ASCII value of s1 => (65)
- Now subtract both.
- 65 - 104 = -39
The following code to compare two strings is compiled, the following syntax error
was displayed – incompatible types – int cannot be converted to boolean.
Page 14 of 30
Identify the statement which has the error and write the correct statement.
Give the output of the program segment.
void calculate()
{
String a = "KING", b = "KINGDOM";
boolean x = a.compareTo(b);
System.out.println(x); }
boolean is an error
Corrected code:
compareToIgnoreCase()
public class compareto_ignore
{
public static void compareto()
{
String s1="hello";
String s2="HEllo";
System.out.println(s1.compareToIgnoreCase(s2)); // 0
}
}
String s6="Hello";
System.out.println(s6.compareTo(s2)); // -32 H value is lesser than small h
System.out.println(s2.compareTo(s6)); // 32 h value is greater than Capital H
String s7="HELLO";
String replace() : This method returns a new string resulting from replacing all
occurrences of old characters in the string with new characters.
Syntax:
public String replace(char oldch, char newch)
Parameters:
oldch : the old character.
newch : the new character.
Return Value
It returns a string derived from this string by replacing every occurrence of oldch
with newch.
public class replace_eg
{
public static void main(String args[])
{
// Initialising String
String Str = new String("Welcome to geeksforgeeks");
// Using replace to replace characters
System.out.print("After replacing all o with T : " );
System.out.println(Str.replace('o', 'T'));
Page 18 of 30
After replacing all e with D : WDlcomD to gDDksforgDDks
System.out.println("ab+".replace('+','i')); // abi
Substring()
String substring() : This method has two variants and returns a new string that
is a substring of this string. The substring begins with the character at the specified
index and extends to the end of this string.
Syntax :
public String substring(int begIndex)
Parameters :
begIndex : the begin index, inclusive.
Return Value :
The specified substring.
Output:
The extracted substring is : geeksforgeeks
Page 19 of 30
Substring(….)
Syntax :
public String substring(int begIndex, int endIndex)
Parameters :
beginIndex : the begin index, inclusive.
endIndex : the end index, exclusive.
Return Value :
The specified substring.
// Initializing String
String Str = new String("Welcome to geeksforgeeks");
Page 20 of 30
Possible application : The substring extraction finds its use in many application
including prefix and suffix extraction. For example to extract a lastname from
name or extract only denomination from a string containing both amount and
currency symbol. The latter one is explained below.
// Initializing String
String Str = new String("Rs 1000");
//Substring from N to M
name2=name1.substring(0,2);
System.out.println("Substring from index 0 to 2 = " +name2);
Page 22 of 30
Starts With: Tests if the string (current string object) starts with the
specified suffix (str) */
boolean startsWith(String str)
The Java startsWith method is used to check whether the string is starting with
user-specified substring or not. Based on this comparison it will return boolean
True or False. The java.lang.String.startsWith() returns true if this string starts
with the specified suffix.
Ends with: Tests if the string (current string object) ends with the
specified suffix (str) */
boolean endswith(String str)
The Java endsWith method is used to check whether the string is ending with
user-specified substring or not. Based on this comparison it will return boolean
True or False. The java.lang.String.endsWith() returns true if this string ends with
the specified suffix.
valueOf() method
The java string valueOf() method converts different types of values into string. By
the help of string valueOf() method, you can convert int to string, long to string,
boolean to string, character to string, float to string, double to string, object to
string and char array to string.
class ValueOfExa {
public static void main(String arg[])
{
int iNum = 30;
System.out.println(sample); // 30
30
9130
4.56789
914.56589*/
Example 2:
public class StringBufferCapacityExample2 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("string buffer");
sb = new StringBuffer("A");
Example 3:
sb.append("Hello");
Page 26 of 30
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.append("string");
System.out.println(sb.capacity());//now (34*2)+2=70
}
}
append(x) method. Lets you add x characters to the end of a
String Buffer object.
}
}
class setcharacter {
public static void main(String[] args)
{
// print string
System.out.println("String = "
+ str.toString());
// print string
System.out.println("After setCharAt() String = "
+ str.toString()); } }
Page 28 of 30
Output:
String = WelcomeGeeks
After setCharAt() String = WeLcomeGeeks
delete method
This method removes the characters in a substring of this StringBuffer. The
substring begins at the specified start and extends to the character at index end - 1
or to the end of the StringBuffer if no such character exists.
If start is equal to end, no changes are made.
// Output: abchijk
class setlengthmethod {
// print string
System.out.println("String length = "
+ str.length() +
" and contains = " + str);
// print string
System.out.println("After setLength() String = "
+ str.toString());
}
}
/* Output:
String length = 12 and contains = WelcomeGeeks
After setLength() String = WelcomeGee */
Page 30 of 30