×

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

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.