0% found this document useful (0 votes)
76 views

Complete String Methods

complete string methods

Uploaded by

kedarprj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Complete String Methods

complete string methods

Uploaded by

kedarprj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Chapter 8 - String Handling - Notes

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.

The java.lang.String class is used to create a string object.

next() and nextLine()


next() can read the input only till the space. It can't read two words separated by
space. Also, next() places the cursor in the same line after reading
input.nextLine() reads input including space between the words (that is, it reads
till the end of line \n).

Java String trim() method with Example

The java lang.string.trim()is a built-in function that eliminates leading and


trailing spaces. The Unicode value of space character is ‘\u0020’. The trim()
method in java checks this Unicode value before and after the string, if it exists
then removes the spaces and returns the omitted 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.

// Java program to demonstrate working


// of java string trim() method

class Gfg {

// driver code
public static void main(String args[])
{

// trims the trailing and leading spaces


String s = " geeks for geeks has all java functions to read ";
System.out.println(s.trim());

// trims the leading spaces


s = " Chetna loves reading books";
System.out.println(s.trim());
Page 2 of 30
}
}
Output:
geeks for geeks has all java functions to read
Chetna loves reading books

Upper to lower case and vice versa conversion

/*Case conversion : Example method illustrating use of toLowercase and


toUpperCase methods */
import java.util.*;
public class Upper_lower
{
public static void main()
{
String name;
System.out.println("Enter your name");
Scanner sc=new Scanner(System.in);
name=sc.nextLine();
System.out.println("Name in Upper Case: " + name.toUpperCase());
System.out.println("Name in Lower Case: " +name.toLowerCase());
}
}
/*LENGTH OF STRING: Example method to illustrate use of length
method */
length()
int length() - Returns the length of the string i.e, the number of characters in the
string.
import java.util.*;
public class Stringlength
{
public void Test()
{
Page 3 of 30
String name;
System.out.println ("Enter a name");
Scanner sc=new Scanner(System.in);
name=sc.nextLine();
System.out.println("Length of string" +name + "is" + name.length());
}
}

/* Character at Index N: Example method illustrating use of charAt


method. */
char charAt(int index) – Returns the character at the specified index. (return the
value of the character at the particular position).

public class characterlength


{
public static void characterAtIndexN(String name)
{

/* System.out.println ("Enter a name");


Scanner sc=new Scanner(System.in);
name=sc.nextLine(); */

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);
}

There are 4 types of lastIndexOf method in java. The signature of lastIndexOf


methods are given below:

No. Method Description

1 int lastIndexOf(int ch) returns last index position for


the given char value

2 int lastIndexOf(int ch, int returns last index position for the
fromIndex) given char value and from index

3 int lastIndexOf(String returns last index position for the


substring) given substring

4 int lastIndexOf(String returns last index position for the


substring, int fromIndex) given substring and from index

Parameters

ch: char value i.e. a single character e.g. 'a'

fromIndex: index position from where index of the char value or substring is

Page 6 of 30
returned

substring: substring to be searched in this string

Returns

last index of the string

public class LastIndexOfExample{

public static void main(String args[]){

String s1="this is index of example";//there are 2 's' characters in this sentence


int index1=s1.lastIndexOf('s');//returns last index of 's' char value

System.out.println(index1);//6

}}

Java String lastIndexOf(int ch, int fromIndex)


Method Example
public class LastIndexOfExample2 {
public static void main(String[] args) {
String str = "This is index of example";
int index = str.lastIndexOf('s',5);
System.out.println(index);
}
}

Java String lastIndexOf(String substring) Method


Example
public class LastIndexOfExample3 {
public static void main(String[] args) {
String str = "This is last index of example";
int index = str.lastIndexOf("of");
System.out.println(index);
}
}
Page 7 of 30
Java String lastIndexOf(String substring, int
fromIndex) Method Example
It returns the last index of the substring from the fromIndex.

public class LastIndexOfExample4 {

public static void main(String[] args) {


String str = "This is last index of example";
int index = str.lastIndexOf("of", 25);
System.out.println(index);
index = str.lastIndexOf("of", 10);
System.out.println(index); // -1, if not found
}
}

/*Concatenation 1: Example method illustrating use of concat method */


String concat(String str) – Concatenates the specified string to the end of this string
(current String object) string.
The concatenation method appends its argument (which must be a string) to the
indicated string and returns a new instance of the class String. In the example this
new string is also called name1 thus overwriting the previous instance of that
name.

public class stringconcat


{
public static void stringconcat()

// 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)

public class stringequals


{
public static void stringequals()
{
String s1="hello";
String s2="hello";
System.out.println(s1.equals(s2));
String s3="Hello";
String s4="hello";
System.out.println(s3.equals(s4));
}
}

Page 9 of 30
/* Equals Ignore Case
boolean equalsIgnoreCase(String str) : Compares the current string object to
str, ignoring case considerations.

The java.lang.String.equalsIgnoreCase() method compares this String to another


String, ignoring case considerations. Two strings are considered equal ignoring
case if they are of the same length and corresponding characters in the two strings
are equal ignoring case.

//import java.lang.*;

public class equalsignore {

public static void main(String args[]) {


String str1 = "GeeKS FOr gEEks";
String str2 = "geeKs foR gEEKs";
String str3 = "ksgee orF geeks";

// if we ignore the cases both the strings are equal.


boolean result1 = str2.equalsIgnoreCase(str1);
System.out.println("str2 is equal to str1 = " + result1);

// 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:

public class calc


{
void calculate()
{
String a = "KING", b = "KINGDOM";
int x = a.compareTo(b);
System.out.println(x);
}
}
Subtract the length of both the strings.
Output is = 4-7 = -3

ASCII VALUE OF SPACE = 32

Example – Space before string


public class comparing
{
public static void main()
{
String s1=" NagaRAM"; // 32-78 (ASCII value of N = 78) =-46
String s2="NagaRAM";
System.out.println(s1.compareTo(s2));
}
}
Page 15 of 30
Example – Space after string

public class comparing


{
public static void main()
{
String s1="Shivani";
String s2="Shivani "; // length is different
System.out.println(s1.compareTo(s2));// 7 -8 (which includes
single space= -1)
}
}

compareToIgnoreCase()
public class compareto_ignore
{
public static void compareto()
{
String s1="hello";
String s2="HEllo";
System.out.println(s1.compareToIgnoreCase(s2)); // 0
}
}

/* Compare Strings: Example method illustrating use of compareTo and


equals methods */
int compareTo(String 1, anotherString)
When using the compareTo method, the method returns an integer indicating the
lexicographic (alphabetic) location of the first letter of the first string with the first
letter of the second string. If the first letters are both different, integer is returned
indicating the relative alphabetic location of the second start letter compared with
the first, negative if the second is lexicographically after the first and positive
otherwise. If both strings are identical then a 0 values is returned. If both have the
same start letter but are not the same either 32 or -32 is returned according to whether
Page 16 of 30
the second is lexicographically before or after the first. The compareTo method can
thus be usefully incorporated into selection statements (if –else, switch).

public class compare


{
public static void compare()
{
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="lemlo";
String s5="flag";
System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); // -5 because h is 5 times lesser than m
System.out.println(s3.compareTo(s1)); // 5 because h is 5 times greater
System.out.println(s3.compareTo(s4)); // 1 because m is 1 time greater than l
System.out.println(s1.compareTo(s5)); // 2 because f is 2 times greater than h

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 s8="IELLO"; String s9="iELLO"; String s10="IaLLO";


System.out.println(s7.compareTo(s8)); // -1 because H value is lesser than I
System.out.println(s8.compareTo(s9)); // -32 because I values is lesser than i
System.out.println(s8.compareTo(s10)); // -32 +4 = -28
System.out.println("DEDICATE".compareTo("DEVOTE")); // -18 since the
third letter V is -18 times lesser than D}}
Page 17 of 30
Java.lang.string.replace() method in Java

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'));

// Using replace to replace characters


System.out.print("After replacing all e with D : " );
System.out.println(Str.replace('e', 'D'));
}
}
Output:
After replacing all o with T : WelcTme tT geeksfTrgeeks

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.

// Java code to demonstrate the


// working of substring(int begIndex)
public class Substr1 {
public static void main(String args[])
{
// Initializing String
String Str = new String("Welcome to geeksforgeeks");

// using substring() to extract substring


// returns geeksforgeeks
System.out.print("The extracted substring is : ");
System.out.println(Str.substring(10));
}
}

Output:
The extracted substring is : geeksforgeeks

Page 19 of 30
Substring(….)

String substring(begIndex, endIndex):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 or
up to endIndex – 1, if the second argument is given.

Syntax :
public String substring(int begIndex, int endIndex)
Parameters :
beginIndex : the begin index, inclusive.
endIndex : the end index, exclusive.
Return Value :
The specified substring.

// Java code to demonstrate the


// working of substring(int begIndex, int endIndex)
public class Substr2 {
public static void main(String args[])
{

// Initializing String
String Str = new String("Welcome to geeksforgeeks");

// using substring() to extract substring


// returns geeks
System.out.print("The extracted substring is : ");
System.out.println(Str.substring(10, 16)); // geeks
System.out.println(Str.substring(2, 2)); // No output
System.out.println(Str.substring(2, 25)); // StringIndexOutOfBoundsException
}
}

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.

// Java code to demonstrate the


// application of substring()
public class Appli {
public static void main(String args[])
{

// Initializing String
String Str = new String("Rs 1000");

// Printing original string


System.out.print("The original string is : ");
System.out.println(Str);

// using substring() to extract substring


// returns 1000
System.out.print("The extracted substring is : ");
System.out.println(Str.substring(3));
}
}
Output :
The original string is : Rs 1000
The extracted substring is : 1000

public class subStringex


{
public static void subString(String name1)
{
System.out.println("\nSubstrings");
//Substring from index 4 onwards
System.out.println("Substring from index 4 onwards = " + name1.substring(4));
Page 21 of 30
//Substring comprising all of input
String name2=name1.substring(0,name1.length());
System.out.println("Entire copy of " + name1 + "=" + name2);

//Substring from N to M
name2=name1.substring(0,2);
System.out.println("Substring from index 0 to 2 = " +name2);

// Substring made up of name2 from above (first three characters


//of name 1) plus substring from the first occurrence of a space
//(' ') in name 1 to three characters beyond it.

name2=name2.concat(name1.substring(name1.indexOf(' '),name1.indexOf(' ')


+3));
System.out.println("name2 = " + 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.

public class startswith


{
public static void main(String args[])
{
String str_Sample = "Java String endsWith example";
//Check if ends with a particular sequence or character
System.out.println("Starts With character 'e': " + str_Sample.startsWith("e")); //
false
System.out.println("Starts With character 'ple': " +
str_Sample.startsWith("ple")); // false
System.out.println("Starts With character 'Java': " +
str_Sample.startsWith("Java")); //
}
}

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.

public class endswith {


public static void main(String args[]) {
String str_Sample = "Java String endsWith example";
//Check if ends with a particular sequence
Page 23 of 30
System.out.println("EndsWith character 'e': " + str_Sample.endsWith("e"));
System.out.println("EndsWith character 'ple': " +
str_Sample.endsWith("ple"));
System.out.println("EndsWith character 'Java': " +
str_Sample.endsWith("Java"));
}
}

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;

double fNum = 4.56789;


String s = "91";

// Returns the string representation of int iNum.


String sample = String.valueOf(iNum);

System.out.println(sample); // 30

// concatenating string with iNum


System.out.println( s + sample); // 9130

// Returns the string representation of the float fnum.


sample = String.valueOf(fNum);
System.out.println(sample); // 4.56789

// concatenating string with fNum


System.out.println(s + sample); //914.56789
Page 24 of 30
}
}
/*Output:

30
9130
4.56789
914.56589*/

Refer the link below for more information:


https://www.geeksforgeeks.org/stringbuffer-insert-java/

String Buffer class – Not part of syllabus. Can be used as a reference


material for Grade 11 & 12

Java StringBuffer capacity() method

/* #1 Capacity : Example method illustrating use of capacity method */


int capacity( ) : Returns maximum no. of characters that can be entered in the
current string object
The capacity() method of Java StringBuffer class returns the current capacity
of the string buffer. The capacity refers to the total amount of characters
storage size in string buffer. An empty StringBuffer class contains the default
16 character capacity. If the number of the character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2.
Example 1:
public class StringBufferCapacityExample1 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
Page 25 of 30
//printing default capacity of string buffer
System.out.println("default capacity: " + sb.capacity());
}
}

Example 2:
public class StringBufferCapacityExample2 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("string buffer");

// printing the current capacity of the string buffer i.e. 16 + 14


System.out.println("capacity: " + sb.capacity());

sb = new StringBuffer("A");

// printing the current capacity of the string buffer i.e. 16 + 1


System.out.println("capacity: " + sb.capacity());
}
}

Example 3:

public class StringBufferCapacityExample3


{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16

sb.append("Hello");

System.out.println(sb.capacity());//now 16 cause the appended string is less than 16

sb.append("java is my favourite language"); // appended string is more than 16 the


formula is used, and the capacity of the buffer space increases

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.

public class appendfuncti {


public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("Hi");

/* Here it appends the char argument as


string to the string buffer */
sbf.append('!');
System.out.println("Result after appending = " + sbf);

}
}

// Java program to demonstrate StringBuffer insert


// for char input.

insert(offset, x) method: Lets you add x characters at a


specified location offset within a StringBuffer object.

public class insertchar {


public static void main(String[] args)
{
StringBuffer str =
new StringBuffer("geeks for geeks");
Page 27 of 30
System.out.println("string = " + str);

// insert boolean value at offset 8


str.insert(8, 'p');

// prints stringbuffer after insertion


System.out.print("After insertion = ");
System.out.println(str.toString());
}
}
// Output: string = geeks for geeks
//After insertion = geeks fopr geeks

setChar(index, c) method: Alters just one character. It


replaces character at index with c in a StringBuffer.

class setcharacter {
public static void main(String[] args)
{

// create a StringBuffer object


// with a String pass as parameter
StringBuffer str
= new StringBuffer("WelcomeGeeks");

// print string
System.out.println("String = "
+ str.toString());

// set char at index 2 to 'L'


str.setCharAt(2, 'L');

// 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.

Here is the detail of parameters −


start − The beginning index, inclusive.
end − The ending index, exclusive.

public class deletemethod {

public static void main(String args[]) {


StringBuffer sb = new StringBuffer("abcdefghijk");
sb.delete(3, 7);
System.out.println(sb);
}
}

// Output: abchijk

setLength(n) method: Sets the length of the content to n by either


truncating current content or extending it with the null character (‘\u0000’). Use
sb.setLength(0); to clear a string buffer.

class setlengthmethod {

public static void main(String[] args)


{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer str
Page 29 of 30
= new StringBuffer("WelcomeGeeks");

// print string
System.out.println("String length = "
+ str.length() +
" and contains = " + str);

// set length equal to 10


str.setLength(10);

// print string
System.out.println("After setLength() String = "
+ str.toString());
}
}
/* Output:
String length = 12 and contains = WelcomeGeeks
After setLength() String = WelcomeGee */

reverse() method: Reverses the contents of String Buffer


public class reversemethod {

public static void main(String args[]) {


StringBuffer sb = new StringBuffer("Java");
sb.reverse();
System.out.println(sb);
}
} //Output: avaJ

Page 30 of 30

You might also like