×

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

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.