×

String Manipulation in Java

String Manipulation in Java

In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of string includes getting the length of a string, finding the character within a string, String concatenation, getting substring, string modification, etc. The string manipulation can be done manually by a developer or programmer. However, doing things manually takes time. Therefore, Java provides a number of predefined methods to do the manipulation of string. A few of those predefined methods are:

  • split()
  • trim()
  • toLowerCase()
  • toUpperCase()
  • subSquence()

Let’s discuss it in detail.

Java String.split() Method

The split() method takes a regular expression as its parameter and returns an array of strings.

FileName: SplitMethodExample.java

 // A basic Java program that shows the working of the split() method.
public class SplitMethodExample
{ 
// main method
public static void main(String argvs[])
{ 
// creating an object of String
String str = new String("Tutorial & Example"); 
// the split() method returns an array of string
String arrStr[] = str.split(" ");
// size of the array
int size = arrStr.length;
// iterating over the element of the string array
for(int i = 0 ; i < size; i++)
{
    System.out.println(arrStr[i]);
}
} 
}  

Output:

 Tutorial
&
Example 

Explanation: In the above program, the split() method splits the input string on the basis of white spaces present in the string. As the input string contains two white spaces, therefore, whatever is present between the index 0 and the first white space is treated as the first element of the resultant string array. Characters from the first white space to the second white space form the second element, and the characters from the second white space till the end of the string form the third element of the resultant string array.

Java String.trim() Method

The trim() method takes no parameter and returns a string. The trim() method removes the trailing and leading spaces from the given string.

FileName: TrimMethodExample.java

 // A basic Java program that shows the working of the trim() method.
public class SplitMethodExample
{ 
// main method
public static void main(String argvs[])
{ 
// The input string contains two leading spaces and two trailing spaces
String str = new String("  Tutorial & Example  "); 
System.out.println("The given string is: " + str + "\n");
// invoking the trim() method
str = str.trim();
System.out.println("The given string is: " + str);
} 
}  

Output:

 The given string is:   Tutorial & Example 
The given string is: Tutorial & Example 

Explanation: The leading and trailing spaces have been removed, and the same is evident by looking at the output.

Java String.toLowerCase() Method

The toLowerCase() method does not accepts any parameter and returns a string. The toLowerCase() method converts the given string into the lower case.

FileName: ToLowerCaseMethodExample.java

 // A basic Java program that shows the working of the toLowerCase() method.
public class ToLowerCaseMethodExample
{ 
// main method
public static void main(String argvs[])
{ 
// The input string contains two leading spaces and two trailing spaces
String str = new String("Tutorial & Example"); 
System.out.println("The given string is: " + str + "\n");
// invoking the toLowerCase() method
str = str.toLowerCase();
System.out.println("The given string is: " + str);
} 
}  

Output:

 The given string is: Tutorial & Example
The given string is: tutorial & example 

Explanation: Observe that letter ‘T’ in ‘Tutorial’ and ‘E’ in ‘Example’ have been converted into ‘t’ and ‘e’, respectively.

Java String.toUpperCase() Method

The toUpperCase() method takes no parameter and returns a string. The toUpperCase() method converts the given string into the upper case.

FileName: ToUpperCaseMethodExample.java

 // A basic Java program that shows the working of the toUpperCase() method.
public class ToUpperCaseMethodExample
{ 
// main method
public static void main(String argvs[])
{ 
// The input string contains two leading spaces and two trailing spaces
String str = new String("Tutorial & Example"); 
System.out.println("The given string is: " + str + "\n");
// invoking the toUpperCase() method
str = str.toUpperCase();
System.out.println("The given string is: " + str);
} 
}  

Output:

 The given string is: Tutorial & Example
The given string is: TUTORIAL & EXAMPLE 

Explanation: Observe that every letter of the words ‘Tutorial’ as well as ‘Example’ has been converted into upper case.

Java String.subSequence() Method

The subSequence() method takes two arguments. One is the startIndex and other is the endIndex. Whatever characters are present between the startIndex and endIndex, startIndex inclusive and endIndex exclusive ([startIndex, endIndex)), are returned. The return type of the method subSquence() is CharSequence.

FileName: SubSequenceMethodExample.java

 // A basic Java program that shows the working of the subSequence() method.
public class SubSequenceMethodExample
{ 
// main method
public static void main(String argvs[])
{ 
// The input string
String str = "Hello and Welcome to Tutorial & Example "; 
System.out.println("The given string is: " + str + "\n");
int startIndex = 0;
int endIndex = 5;
// invoking the subSequence() method
CharSequence cs = str.subSequence(startIndex, endIndex);
System.out.println("Subsequence from index "+ startIndex + " to " + endIndex + " is: " + cs);
// Updating the startIndex and endIndex
startIndex = 10;
endIndex = 17;
// indices from 10 to 16 are considered
cs = str.subSequence(startIndex, endIndex);
System.out.println("Subsequence from index "+ startIndex + " to " + endIndex + " is: " + cs);
// Updating the startIndex and endIndex
startIndex = 21;
endIndex = 29;
// indices from 21 to 28 are considered
cs = str.subSequence(startIndex, endIndex);
System.out.println("Subsequence from index "+ startIndex + " to " + endIndex + " is: " + cs);
} 
}    

Output:

 The given string is: Hello and Welcome to Tutorial & Example
Subsequence from index 0 to 5 is: Hello
Subsequence from index 10 to 17 is: Welcome
Subsequence from index 21 to 29 is: Tutorial 

Explanation: The above program prints the characters of different works present in the input string on the basis of their indices.


Related Topics

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.